leetcode-搜索插入位置-二分查找


顺序查找:

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        l = len(nums)
        if l == 0:
            return False
        if target in nums:
            return nums.index(target)
        else:
            if target<nums[0]:
                return 0
            elif target>nums[-1]:
                return l
            else:
                for i in range(l-1):
                    if nums[i]<target<nums[i+1]:
                        return i+1

二分查找:

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        l = len(nums)
        lo = 0
        hi = l
        if l == 0:
            return False
        while(lo<hi):
            mid = lo+(hi-lo)/2
            if nums[mid]>target:
                hi = mid
            elif nums[mid]<target:
                lo=mid+1
            else:
                return mid
        return lo

你可能感兴趣的:(leetcode)