35. 搜索插入位置

https://leetcode-cn.com/problems/search-insert-position/

解法一:

一次遍历,找插入位置即可

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        i = 0
        while i < len(nums) and target > nums[i]:
            i += 1
        return i

解法二:二分

注意特殊处理,h初始为len(nums),另外l,h的移动方式也与传统二分不同。

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

最后更新于