Easy
python3
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for i in range(len(nums)):
if nums[i] >= target:
return i
return len(nums)
对于这种在排序好的列表中搜索目标值,一眼就是二分搜索题
直接使用python二分库,AC!
python3
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
return bisect.bisect_left(nums,target)
面试中肯定不能用库了,手撕也行,AC!
python3
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
lo = 0
hi = len(nums) - 1
if nums[-1] < target:
return len(nums)
while lo < hi:
mid = lo + (hi-lo) // 2
if target <= nums[mid]:
hi = mid
else:
lo = mid + 1
return lo