Given a sorted array of integers and a target value, return the index of the target if it exists in the array. If the target is not present, return -1.
The array is sorted in non-decreasing order. The solution must use the iterative binary search approach, repeatedly dividing the search space in half until the target is found or the search space becomes empty.
Example 1
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: The target value 9 exists at index 4 in the array.
Example 2
Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: The target value 2 does not exist in the array, so return -1.
Example 3
Input: nums = [1], target = 1
Output: 0
Explanation: The array contains only one element, which matches the target, so return index 0.
Approach, complexity and clean code in every language. Sign in to unlock the editorial.
Your submissions, results and runtime history live here. Sign in to start your streak.
1 1
0
1 2 3 2
1