leet-code/binary-search/sol.go

23 lines
393 B
Go
Raw Normal View History

2021-11-05 14:54:48 +00:00
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
}