-
Notifications
You must be signed in to change notification settings - Fork 0
/
033. Search in Rotated Sorted Array.cpp
45 lines (44 loc) · 1.33 KB
/
033. Search in Rotated Sorted Array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Solution 1.
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
if(n == 0) return -1;
int lo = 0, hi = n - 1;
int mid = (lo + hi) / 2;
while(lo < hi){
if(nums[mid] > nums[hi]) lo = mid + 1;
else hi = mid;
mid = (lo + hi) / 2;
}
int pos = (target >= nums[0] && lo != 0) ? lower_bound(nums.begin(), nums.begin() + lo, target) - nums.begin()
: lower_bound(nums.begin() + lo, nums.end(), target) - nums.begin();
return nums[pos] == target ? pos : -1;
}
};
// Solution 2.
class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
if(n == 0) return -1;
int lo = 0, hi = n - 1;
int mid = (lo + hi) / 2;
while(lo < hi){
if(nums[mid] > nums[hi]) lo = mid + 1;
else hi = mid;
mid = (lo + hi) / 2;
}
int ro = lo;
lo = 0, hi = n - 1;
mid = (lo + hi) / 2;
while(lo <= hi){
int realMid = (mid + ro) % n;
if(nums[realMid] == target) return realMid;
if(nums[realMid] > target) hi = mid - 1;
else lo = mid + 1;
mid = (lo + hi) / 2;
}
return -1;
}
};