LeetCode #35 Search Insert Position
题目
解题方法
二分查找即可解,需注意待插入位置应为low或者high+1,因为插入位置可以是len(nums)但不可以是-1。
代码
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
ret = 0
low, high = 0, len(nums)-1
while low <= high:
mid = (low + high) // 2
if target == nums[mid]:
ret = mid
break
elif target > nums[mid]:
low = mid + 1
ret = low
else:
high = mid - 1
ret = high + 1
return ret