cheetcode

28. Binary SearchEasy

Find the target index in a sorted array or return -1.

Given an array of integers nums sorted in ascending order and an integer target, return the index of target if it is in the array.

If target does not exist in nums, return -1.

The input or answer space has an order you can cut in half. Define what makes a midpoint too small, too large, or good enough before writing the loop.

Examples

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

Constraints

  • 1 <= nums.length <= 10,000
  • -10,000 <= nums[i], target <= 10,000
  • All nums values are unique.