给定一个排序数组和一个目标值 在数组中找到目标值 并返回其索引 如果目标值不存在于数组中,返回它将会被按顺序插入的位置,请必须使用时间复杂度为 O(log n) 的算法
示例 1:
输入: nums = [1,3,5,6], target = 5
输出: 2
示例 2:
输入: nums = [1,3,5,6], target = 2
输出: 1
示例 3:
输入: nums = [1,3,5,6], target = 7
输出: 4
python代码:
class Solution:
def searchInsert(self, nums, target):
start_index = 0
end_index = len(nums) - 1
while start_index <= end_index:
index = start_index + (end_index - start_index) // 2
if target > nums[index]:
start_index = index + 1
elif target < nums[index]:
end_index = index - 1
else:
return index
return start_index
go代码:
func pivotIndex(nums []int, target int) int {
n := len(nums)
left, right := 0, n-1
res := n
for left <= right {
mid := (right + left) / 2
if target <= nums[mid] {
res = mid
right = mid - 1
} else {
left = mid + 1
}
}
return res
}