diff --git a/binary-search/sol.go b/binary-search/sol.go new file mode 100644 index 0000000..6e5fb72 --- /dev/null +++ b/binary-search/sol.go @@ -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 +}