题目:
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
solution:
class Solution:
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
"""
第一种方法:
如果nums中的某个元素大于等于target,返回该元素的下标,否则应该插入到最后,也就是返回len(nums)
for i in nums:
if i >= target:
return nums.index(i)
return len(nums)
"""
"""
第二种方法:
用一行代码搞定的操作:
return len([x for x in nums if x < target])
另一种高级操作:
'bisect',--- 查找该数值将会插入的位置(索引)并返回,0~全长 'bisect_left'返回左侧元素, 'bisect_right'返回右侧元素
'insort',---插入元素,不会影响原排列 'insort_left', 'insort_right同上
return bisect.bisect_left(nums, target)
"""
"""
第三种方法:
根据topic中给出的提示是binary search:
"""
start = 0
end = len(nums)-1
while start <= end:
mid = (start+end)//2#注意是整除
if nums[mid] == target:
return mid
if nums[mid] < target:
start += 1
else:
end -= 1
return start