一.题目内容
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 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 4:
Input: [1,3,5,6], 0 Output: 0
中文解释:给定一个有序数列以及一个整数值,判断该整数加入后在数组中的位置。
二.解题思路
因为给定的数列是有序的,所以直接使用二分查找算法即可。
关于二分查找算法内容这里不再赘述,请参考:https://blog.youkuaiyun.com/mengxiang000000/article/details/52751310
三.代码实现
class Solution(object):
def searchInsert(self, nums, target):
lo, hi = 0, len(nums)-1
while lo <= hi:
mid = (lo + hi) / 2
if nums[mid] > target:
hi = mid-1
elif nums[mid] < target:
lo = mid+1
else:
return mid
return lo