MEDIUM
Search in Rotated Sorted Array
There is an integer array nums sorted in ascending order (with distinct values), which is rotated at an unknown pivot index k (0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed).
Given the array nums after the rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example
Input:
nums = [4,5,6,7,0,1,2], target = 0
Output:
4
Explanation:
0 is at index 4 in the rotated array.
Constraints
- 1 ≤ nums.length ≤ 5000
- -10⁴ ≤ nums[i] ≤ 10⁴
- All values of nums are unique.
- nums is guaranteed to be rotated at some pivot.
- -10⁴ ≤ target ≤ 10⁴
Solution: Binary Search
- Time Complexity: O(log n)
- Space Complexity: O(1)
C++
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0, r = nums.size() - 1;
while (l <= r) {
int m = l + (r - l) / 2;
if (nums[m] == target) return m;
if (nums[l] <= nums[m]) {
if (nums[l] <= target && target < nums[m]) r = m - 1;
else l = m + 1;
} else {
if (nums[m] < target && target <= nums[r]) l = m + 1;
else r = m - 1;
}
}
return -1;
}
};