[LeetCode] 35. Search Insert Position_Easy tag: Binary Search

思路就是Binary Search, 找到first position s.t A[i] >= target

Code

1) 利用python的built-in function     bisect.bisect_left

class Solution:
    def searchInsert(self, nums, target):
        return bisect.bisect_left(nums, target)

2) 利用python的built-in function     bisect.bisect

class Solution:
    def searchInsert(self, nums, target):
       return nums.index(target) if target  in nums else bisect.bisect(nums, target)

3) basic 做法, first position s.t A[i] >= target

        if not nums: return 0
        l, r = 0, len(nums)-1
        while l + 1 < r:
            mid = l + (r - l)//2
            if nums[mid] < target:
                l = mid
            elif nums[mid] > target:
                r = mid
            else:
                return mid  # 因为没有duplicates
        if nums[l] >= target:
            return l
        elif nums[r] >= target:
            return r
        else:
            return r+1  # 因为有可能比最大的还大

猜你喜欢

转载自www.cnblogs.com/Johnsonxiong/p/9552824.html