Given a sorted array of distinct integers nums and a target, return the index of target, or −1 if it is not present. You must write an O(log n) algorithm.
Keep a window [lo, hi] that must contain the target if it exists. Compare the middle element and throw away the half that cannot hold it.
1function search(nums: number[], target: number): number {2let lo = 0, hi = nums.length - 1;3while (lo <= hi) {4const mid = (lo + hi) >> 1;5if (nums[mid] === target) return mid;6if (nums[mid] < target) lo = mid + 1;7else hi = mid - 1;8}9return -1;10}
Search the whole array.
Space: play/pause · ←/→: step