首页 > 其他 > 详细

Leetcode_num12_Search Insert Position

时间:2014-09-25 20:04:08      阅读:206      评论:0      收藏:0      [点我收藏+]

题目:

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!