417. Binary Search in Sorted Array

EasyBinary SearchArrayBinary Search

Given a sorted array of integers nums and an integer target, return the index of target if it exists in the array, or -1 if it does not exist. You must write an algorithm with O(log n) runtime complexity.

Input: A sorted integer array nums and an integer target.

Output: Return the index of target in nums, or -1 if not found.

Examples

Example 1
Input: [1,3,5,7,9,11], 7
Output: 3
Explanation: nums[3] = 7. Binary search: lo=0,hi=5 → mid=2(5<7)→lo=3, mid=4(9>7)→hi=3, mid=3(7==7)→return 3.
Example 2
Input: [2,4,6,8,10], 5
Output: -1
Explanation: 5 is not in the array. Binary search exhausts all possibilities and returns -1.
Example 3
Input: [-10,-5,0,5,10], -5
Output: 1
Explanation: nums[1] = -5. mid=2(0>-5)→hi=1, mid=0(-10<-5)→lo=1, mid=1(-5==-5)→return 1.

Constraints

Asked by

BloombergGoogleCognizantMicrosoftInfosysMeta
Solve this problem in the editor →