Binary Search
Given a sorted (ascending) array of distinct integers nums and an integer target, return the index of target if it is present, otherwise return -1. The algorithm must run in O(log n) time.
Open official problem prompt ↗Find whether and where a target value lives in a sorted array, in logarithmic time.
Looking up a word in a physical dictionary: open to the middle, see whether your word comes before or after, and repeat on the surviving half instead of flipping page by page.
- Input
- nums = [-1,0,3,5,9,12], target = 9
- Output
- 4
- Why
- nums[4] equals 9, so its index is returned.
1 <= nums.length <= 10^4-10^4 < nums[i], target < 10^4All integers in nums are uniquenums is sorted in ascending order