Search in Rotated Sorted Array
Given a rotated sorted array nums (with distinct values) and a target, return the index of target or -1 if not found.
You must achieve O(log n) time complexity.
Example
4,5,6,7,0,1,2 0
4
- Input:
numsis the sorted list rotated to start at ;target. Indices run to . - The rotation leaves two ascending runs: at indices to , then at indices to .
- Every value in the first run is at least (its first element), and every value in the second run is at most (the last element of the array). Since , the target cannot be in the first run; it can only be in the second.
- The second run begins with the smallest value of the whole array, , at index . That matches the target, so the output is
4. - Notice that for
target, rules out the first run and rules out the second, so the answer would be . The bound means reaching such conclusions without checking every element.
Constraints
- 1 <= len(nums) <= 5000
- -10^4 <= nums[i] <= 10^4
- All values are unique
- nums was rotated at some pivot