題目鏈接
難度:簡單 ??????類型: 數組、二分查找
給定一個排序數組和一個目標值,在數組中找到目標值,并返回其索引。如果目標值不存在于數組中,返回它將會被按順序插入的位置。
你可以假設數組中無重復元素。
示例1
輸入: [1,3,5,6], 5
輸出: 2
示例2
輸入: [1,3,5,6], 2
輸出: 1
示例3
輸入: [1,3,5,6], 7
輸出: 4
示例4
輸入: [1,3,5,6], 0
輸出: 0
解題思路
普通的二分查找,找到了就返回索引,找不到就返回搜索到最后指針停留的位置
代碼實現
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums)
while left<right:
mid = (left+right)//2
if nums[mid]>=target:
right = mid
else:
left = mid + 1
return left