Example 1
- Input
- nums = [4,5,6,7,0,1,2], target = 0
- Output
- 4
The value 0 sits at index 4, so the answer is 4.
You are given a rotated sorted array of distinct integers and a target value. Return the index of the target in the array, or negative one when the target is absent.
There is an integer array nums sorted in ascending order with distinct values. Before it reaches you, nums is possibly rotated at an unknown pivot index, so the tail of the sorted order may wrap to the front.
Given the possibly rotated array nums and an integer target, return the index of target if it is in nums, or -1 if it is not. The required solution runs in time.
1 <= nums.length <= 5000-10^4 <= nums[i] <= 10^4nums are unique.nums is an ascending array that is possibly rotated.-10^4 <= target <= 10^4The value 0 sits at index 4, so the answer is 4.
The target 3 lies in the gap between 2 and 4 in the original sorted order. Rotation changes positions but adds no values, so the candidate interval eventually becomes empty and the answer is -1.
The single element 1 is not the target, so the answer is -1.
The midpoint is initially index 0. Its one-element left half is sorted, but target 1 is outside it, so the search retains index 1 and finds the match. This exercises inclusive half detection on two elements.
Rotation cuts one ascending sequence into two ascending pieces and swaps their order. In Example 1, [4,5,6,7] is followed by [0,1,2], so comparing only the midpoint 7 with target 0 does not tell us which side to keep. At each midpoint, however, at least one half has no wrap and is sorted. Its endpoints tell us whether target belongs in that half; otherwise we keep the other half.
Reveal Linear Scan: intuition, complexity, and code
mid: at least one of the two halves must be in sorted order, so test it with nums[left] <= nums[mid].target sits between its endpoints before deciding which half to drop.left <= right loop with mid - 1 and mid + 1 updates so a single remaining element is still examined.[1] with a missing target returns -1 after one comparison.0 in [4,5,6,7,0,1,2], is found once the interval narrows to it.< instead of <= for the sorted-half test, which misclassifies a one-element half.mid instead of mid - 1 or mid + 1, which can loop forever on two elements.When rotation breaks global order, identify the sorted half of each interval and keep only the side that can still hold the target.