Created
February 24, 2020 19:59
-
-
Save mustafa-zidan/46c4024895650ac4a15d62590deb7403 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
@ahmgeek