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

猜你喜欢

转载自www.cnblogs.com/nilhxzcode/p/12904558.html
今日推荐