35. Search Insert Position
Contents
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
Input: [1,3,5,6], 5
Output: 2example 2
Input: [1,3,5,6], 2
Output: 1example 3
Input: [1,3,5,6], 7
Output: 4example 4
Input: [1,3,5,6], 0
Output: 0Solution
Binary search
Using binary search with additional :
- return
0if target less thennums[0] - return
len(nums)if target grater thennums[len(nums)-1] - where usually return
-1( not exist element) – returnleft
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
}