leetcode 每日一题 35. 搜索插入位置

二分法

代码:

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        if not nums:
            return 0 
        l,r = 0,len(nums)-1
        while l <= r:
            mid = (l+r)//2
            if nums[mid]==target:
                return mid
            elif nums[mid]<target:
                l = mid + 1
            else:
                r = mid - 1
        return r+1

 

posted @ 2020-05-17 11:44  nil_f  阅读(102)  评论(0编辑  收藏  举报