search-insert-position

This commit is contained in:
Gleb Koval 2021-11-05 15:18:31 +00:00
parent 51695319c2
commit 1d06af2727
No known key found for this signature in database
GPG Key ID: 7C89CDC822F8392B
1 changed files with 19 additions and 0 deletions

View File

@ -0,0 +1,19 @@
package main
// Time: O(log(n))
// Space: O(1)
func searchInsert(nums []int, target int) int {
move := 0
for l := len(nums); l > 0; l = len(nums) {
idx := l / 2
if nums[idx] < target {
nums = nums[idx+1:]
move += idx + 1
} else if nums[idx] > target {
nums = nums[:idx]
} else {
return move + idx
}
}
return move
}