forked from Aniket123cloud/hacktoberfestani-2k22
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path33. Search in Rotated Sorted Array.cpp
59 lines (50 loc) · 1.46 KB
/
33. 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//binary search
class Solution {
public:
int findMinIdx(vector<int>& nums){
int l = 0, r = nums.size()-1;
while(l <= r){
int mid = l + (r-l)/2;
if(nums[mid] > nums.back()){
//ex: [4,5,6,7,0,1,2], 7 > 2
//so search in right part
l = mid+1;
}else{
//right part is monotonic,
//so search in left part
r = mid-1;
}
}
return l;
};
int search(vector<int>& nums, int target) {
int n = nums.size();
if(n == 0) return -1;
int minIdx = findMinIdx(nums);
if(nums[minIdx] == target) return minIdx;
// cout << "minIdx: " << minIdx << endl;
//this is the important part!!
int l, r;
if(nums[n-1] >= target){
//we can find target in left part
l = minIdx + 1;
r = n-1;
}else{
//we can find target in left part
l = 0;
r = minIdx-1;
}
while(l <= r){
int mid = l + (r-l)/2;
// cout << l << " " << mid << " " << r << endl;
if(nums[mid] == target){
return mid;
}else if(nums[mid] > target){
r = mid-1;
}else{
l = mid+1;
}
}
return -1;
}
};