23 lines
393 B
Go
23 lines
393 B
Go
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
|
|
}
|