Skip to content

704. Binary Search 👍

  • Time: $O(\log n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  int search(vector<int>& nums, int target) {
    const auto it = ranges::lower_bound(nums, target);
    return (it == nums.cend() || *it != target) ? -1
                                                : distance(nums.begin(), it);
  }
};
1
2
3
4
5
6
class Solution {
  public int search(int[] nums, int target) {
    final int i = Arrays.binarySearch(nums, target);
    return i < 0 ? -1 : i;
  }
}
1
2
3
4
class Solution:
  def search(self, nums: list[int], target: int) -> int:
    i = bisect.bisect_left(nums, target)
    return -1 if i == len(nums) or nums[i] != target else i