Search in Rotated Sorted Array
Given an integer array nums that was originally sorted in ascending order with distinct values, then possibly rotated at an unknown pivot, and a target value, return the index of target if it is in nums, otherwise return -1. You must run in O(log n) time.
Open official problem prompt ↗Locate a target in a sorted-then-rotated array in logarithmic time by exploiting the structure that one half is always sorted.
Imagine a clock face cut and rejoined at a random hour. Even though the '12' may not be at the top, any half you look at still runs in order, so you can tell at a glance whether your hour falls in that stretch.
- Input
- nums = [4, 5, 6, 7, 0, 1, 2], target = 0
- Output
- 4
- Why
- The value 0 sits at index 4 in the rotated array.
1 <= nums.length <= 5000-10^4 <= nums[i] <= 10^4All values of nums are uniquenums is an ascending array possibly rotated-10^4 <= target <= 10^4