[LeetCode] Search in Rotated Sorted Array

33. Search in Rotated Sorted Array

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums 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). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int search(vector<int>& nums, int target, int start, int end) {
if(start == end) return nums[start] == target ? start : -1;
int mid = (start + end) / 2;
if(nums[start] <= nums[mid] && nums[start] <= target && target <= nums[mid]) {
auto it = lower_bound(nums.begin() + start, nums.begin() + mid, target);
return *it == target ? it - nums.begin() : -1;
}
if(nums[mid + 1] <= nums[end] && nums[mid + 1] <= target && target <= nums[end]) {
auto it = lower_bound(nums.begin() + mid + 1, nums.begin() + end, target);
return *it == target ? it - nums.begin() : -1;
}
if(nums[mid + 1] <= nums[end])
return search(nums, target, start, mid);
return search(nums, target, mid + 1, end);
}
public:
int search(vector<int>& nums, int target) {
return search(nums, target, 0, nums.size() - 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/17/PS/LeetCode/search-in-rotated-sorted-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.