arrays
binary-search
You are given an integer array nums sorted in ascending order (with distinct values), then rotated at some unknown pivot index. Given nums and an integer target, return the index of target in nums, or -1 if it is not present. You must write an algorithm with O(log n) runtime complexity.
Input / output
- Input:
nums: integer[](rotated ascending, distinct values),target: integer - Output:
integer, the index oftarget, or-1
Examples
nums = [4,5,6,7,0,1,2], target = 0returns4.nums = [4,5,6,7,0,1,2], target = 3returns-1because3is not in the array.nums = [1], target = 0returns-1.
Constraints
1 <= nums.length <= 5,000-10,000 <= nums[i] <= 10,000- All values of
numsare unique. numsis an ascending array possibly rotated at an unknown pivot.
Follow-up
How would your approach change if duplicate values were allowed, and why can that force worst-case O(n)?
Examples
Example 1
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2 (not present)
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Example 3 (single element)
Input: nums = [1], target = 0
Output: -1
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.