Question
Given a sorted array and a target value, return the index if the
target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example
Input: [1,3,5,6], 5 Output: 2
Python Code
# 从头遍历
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
i = 0
while i <= len(nums)-1 and nums[i] <= target:
if nums[i] < target:
i+=1
elif nums[i] >= target:
break
return i
# 二叉树
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
l,r = 0,len(nums)-1
if target <= nums[l]:
return l
if target >= nums[r] and target != nums[r]:
return r+1
elif target >= nums[r] and target == nums[r]:
return r
while l <= r:
m = int((l+r)/2)
if nums[m] == target:
return m
if nums[m] < target and nums[m+1] > target:
return m+1
elif nums[m] < target:
l=m
elif nums[m] > target:
r=m