binary-search

This commit is contained in:
Gleb Koval 2021-11-05 14:54:48 +00:00
parent b81e5b836a
commit e95b6e4f96
No known key found for this signature in database
GPG Key ID: 7C89CDC822F8392B
1 changed files with 22 additions and 0 deletions

22
binary-search/sol.go Normal file
View File

@ -0,0 +1,22 @@
package main
// Time: O(log(n))
// Space: O(1)
func search(nums []int, target int) int {
move := 0
for l := len(nums); l > 1; 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
}
}
if len(nums) == 1 && nums[0] == target {
return move
}
return -1
}