LeetCode 704 Binary Search - Implementation

The approach

Compare middle to target. Narrow the search range by half each iteration.

function search(nums, target): left = 0 right = len(nums) - 1 while left <= right: mid = (left + right) // 2 if nums[mid] == target: return mid elif nums[mid] < target: left = mid + 1 else: right = mid - 1 return -1

O(logn)O(\log n) time, O(1)O(1) space.