给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 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
示例 4:
输入: nums = [1,3,5,6], target = 0
输出: 0
示例 5:
输入: nums = [1], target = 0
输出: 0
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-insert-position
python
# 搜索插入顺序
class Solution:
def searchInsert(self, nums: [int], target: int) -> int:
n = len(nums)
left, right = 0, n-1
while left <= right:
mid = left + ((right-left) >> 1)
if target < nums[mid]:
right = mid - 1
elif target > nums[mid]:
left = mid + 1
else:
return mid
# 4种情况
# 1.target在所有元素前 [0,-1]
# 2.target等于某个元素 mid
# 3.target介于某2个元素之间 [left, right] -> right+1
# 4.target在所有元素后 同上
return right + 1
# 暴力法 时间O(n),空间O(1)
def searchInsert1(self, nums, target):
"""
遍历解决3种情况,1.比首个元素小的,2.等于某个元素, 3.介于某两个元素之间
:param nums:
:param target:
:return:
"""
n = len(nums)
for i in range(n):
if nums[i] >= target:
return i
# 情况4,大于最后一个元素
return n
if __name__ == "__main__":
nums = [2,3,6,7,8,14,16]
target1 = 0
target2 = 9
target3 = 8
target4 = 18
test = Solution()
print(test.searchInsert1(nums, target1))
print(test.searchInsert1(nums, target2))
print(test.searchInsert1(nums, target3))
print(test.searchInsert1(nums, target4))
print('*'*20)
print(test.searchInsert(nums, target1))
print(test.searchInsert(nums, target2))
print(test.searchInsert(nums, target3))
print(test.searchInsert(nums, target4))
golang
package main
import "fmt"
func main() {
nums := []int{2, 3, 6, 7, 8, 14, 16}
target1 := 0
res1 := searchInsert(nums, target1)
fmt.Println(res1)
}
func searchInsert(nums []int, target int) int {
var n int = len(nums)
left := 0
right := n - 1
for left <= right {
var mid int = left + (right-left)>>1
if target > nums[mid] {
left = mid + 1
} else if target < nums[mid] {
right = mid - 1
} else {
return mid
}
}
return right + 1
}
func searchInsert1(nums []int, target int) int {
var n int = len(nums)
for i, v := range nums {
if v >= target {
return i
}
}
return n
}