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.
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.
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.
Sign in to submit, save progress and mark problems as solved. You can still run your code.
Loading editor...
nums =
[-1,0,3,5,9,12]
target =
9
Expected
4