LeetCode 704

Binary Search

Concepts:

Binary Search

Description: Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

Optimal Approach

Initialize l and r to the first and last element of the array. While l <= r, calculate mid = (l + r) / 2. If it is the target, return it. If the mid element is less than the target, set l = mid + 1. If the mid element is greater than the target, set r = mid - 1. Return -1 if the target is not found.

Time: O(log n)

Space: O(1)

All Problems