1 question
Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position at which it will be inserted sequentially.
Please use an algorithm with a time complexity of O(log n).
Example 1:
输入: nums = [1,3,5,6], target = 5
输出: 2
Example 2:
输入: nums = [1,3,5,6], target = 2
输出: 1
Example 3:
输入: nums = [1,3,5,6], target = 7
输出: 4
Example 4:
输入: nums = [1,3,5,6], target = 0
输出: 0
Example 5:
输入: nums = [1], target = 0
输出: 0
hint:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is an ascending array without repeated elements
-104 <= target <= 104
2 answers
Using the cursor method
func searchInsert(nums []int, target int) int {
var a int =0
if len(nums)==0{
return 0
}else{
for i:=0;i<len(nums);i++{
if nums[i]<target{
a++
}else {
return a
}
}
}
return a
}
3Related links
Source: LeetCode
link: https://leetcode-cn.com/problems/search-insert-position