Skip to main content

Binary Search

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.

Problems32 / 152
Sign in

Binary Search

EASYArrayBinary Search

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.

Example 1

Input:  nums = [-1,0,3,5,9,12], target = 9
Output: 4

Example 2

Input:  nums = [-1,0,3,5,9,12], target = 2
Output: -1
Show hint

Use two pointers (left and right). Calculate mid, compare with target. If equal, return mid. If target < nums[mid], search left half, else search right half.

Draft saves automatically

Loading editor...

Submit also runs hidden tests
nums =
[-1,0,3,5,9,12]
target =
9
Expected
4
Run with your own input (JSON)