Skip to content

Instantly share code, notes, and snippets.

@ahmgeek
Forked from mustafa-zidan/search_insert.go
Created February 24, 2020 20:00
Show Gist options
  • Save ahmgeek/c4b7c5e59ad40316fc136eb241b9a122 to your computer and use it in GitHub Desktop.
Save ahmgeek/c4b7c5e59ad40316fc136eb241b9a122 to your computer and use it in GitHub Desktop.
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.
func searchInsert(nums []int, target int) int {
start, end := 0, len(nums)
if len(nums) == 0 || target < nums[start] {
return 0
} else if target > nums[end-1] {
return len(nums)
}
return getIndex(start, end, target, nums)
}
func getIndex(start, end, target int, nums []int) int {
pivot := (start+end) / 2
if start >= end || pivot > end{
return end
} else if nums[pivot] == target {
return pivot
} else if nums[pivot] > target {
return getIndex(start, pivot, target, nums)
} else {
return getIndex(pivot+1, end , target, nums)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment