AlgoFrames

Implement binary search

Standard · Write code · about 10 min

Given a sorted array of distinct integers nums and a target, return the index of target in nums, or -1 if it is not there.

The solution must run in O(log n) time.

Example 1

Input:

[[1,3,4,7,9,11,15,20],9]

Output:

4

Example 2

Input:

[[1,3,4,7,9,11,15,20],8]

Output:

-1

8 would sit between 7 and 9, but it is not in the array.

Constraints

  • 0 ≤ nums.length ≤ 10,000
  • -10,000 ≤ nums[i], target ≤ 10,000
  • nums is sorted ascending with distinct values

Learn the idea first: Binary search, a visual lesson.

More Binary search problems