问题描述
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.
例子
nums = [1,3,5,6] #5–>2;2–>1;7–>4;0–>0
实际上就是前面range search的变体。思想还是二分查找,这里稍加判断即可。
binary search
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left,right = 0,len(nums)-1
while(left<=right):
mid = (left + right)//2
if nums[mid] == target:
print(mid)
return mid
elif nums[mid] < target:
left = mid+1
else :
right = mid-1
print(right+1)
return right+1
S = Solution()
# nums = [1,3,5,6]#5-->2;2-->1;7-->4;0-->0
nums = [1,3,5,6]
target = 5
S.searchInsert(nums,target)
结果分析
Runtime: 40 ms, faster than 54.59% of Python online submissions for Search Insert Position.
Memory Usage: 12.3 MB, less than 50.74% of Python online submissions for Search Insert Position.