Problem
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
1
2
|
Input: [1,3,5,6], 5
Output: 2
|
example 2
1
2
|
Input: [1,3,5,6], 2
Output: 1
|
example 3
1
2
|
Input: [1,3,5,6], 7
Output: 4
|
example 4
1
2
|
Input: [1,3,5,6], 0
Output: 0
|
Solution
Binary search
Using binary search with additional :
- return
0
if target less then nums[0]
- return
len(nums)
if target grater then nums[len(nums)-1]
- where usually return
-1
( not exist element) – return left
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
func searchInsert(nums []int, target int) int {
left := 0
right:=len(nums)-1
if target>nums[right] {
return len(nums)
}
if target < nums[left] {
return 0
}
for left<=right {
med := (left+right)/2
if nums[med] == target {
return med
}
if nums[med]>target {
right=med-1
continue
}
if nums[med]<target {
left=med+1
continue
}
}
return left
}
|