Locate a Value's Position in a Sorted Array

Implement search

Given an array of integers nums sorted in ascending order and an integer target, return the index of target in nums, or -1 if it isn't present. Your algorithm must run in O(log n) time — a plain left-to-right scan won't be fast enough. Use the fact that the array is sorted to eliminate half the remaining range on every comparison.

Example 1:

Input: nums = [-6,0,3,7,12,15], target = 7

Output: 3

Example 2:

Input: nums = [-6,0,3,7,12,15], target = 9

Output: -1

Example 3:

Input: nums = [5], target = 5

Output: 0

+ 4 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁴
  • -10⁴ ≤ nums[i], target ≤ 10⁴
  • All the values in nums are unique, sorted in ascending order

nums =

[-6, 0, 3, 7, 12, 15]

target =

7