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.
Here are few examples.[1,3,5,6]
, 5 → 2[1,3,5,6]
, 2 → 1[1,3,5,6]
, 7 → 4[1,3,5,6]
, 0 → 0
题意分析:
本题是在一个递增数组中查找目标值target的下标,如果找不到那么返回target应该插入的下标,使得插入之后依然保持递增。可以得到两个信息:1.数组不会有重复值;2.数组是严格单调递增的。
解答:
如果看过【LeetCode题意分析&解答】34. Search for a Range这篇解析之后,应当立即想到,本题其实就是一个变种,其实比那道题更为简单。这道题相当于普通的二分查找变了一下条件,和上道题寻找左边界的代码几乎一致。
AC代码:
class Solution(object):
def searchInsert(self, nums, target):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) / 2
if nums[mid] < target:
left = mid + 1
else:
right = mid
return left + 1 if nums[left] < target else left