码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode_num12_Search Insert Position

时间:2014-09-25 21:12:57      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二叉树   

题目:

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

比较直观的方法如下:

class Solution:
    # @param A, a list of integers
    # @param target, an integer to be inserted
    # @return integer
    def searchInsert(self, A, target):
        rs=0 #结果
        L=len(A)
        for i in range(L):
            if target<A[0]:
                rs=0
                break
            elif target>A[L-1]:
                rs=L
                break
            elif target==A[i]:
                rs=i
                break
            elif target>A[i] and target<A[i+1]:
                rs=i+1
                break
        return rs

但是该方法的复杂度为o(n)

复杂度为o(logn)的方法需要利用二分法

代码如下:

class Solution:
    # @param A, a list of integers
    # @param target, an integer to be inserted
    # @return integer
    def searchInsert(self, A, target):
        L=len(A)
        low=0
        high=L-1
        while(low<=high):
            mid=low+(high-low)/2
            if target<A[mid]:
                high=mid-1
            elif target>A[mid]:
                low=mid+1
            else:
                return mid
        return low


Leetcode_num12_Search Insert Position

标签:leetcode   二叉树   

原文地址:http://blog.csdn.net/eliza1130/article/details/39554719

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!