forked from prince-codes23/HacktoberFest22
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch in Rotated Sorted Array.cpp
60 lines (56 loc) · 1.01 KB
/
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
60
#A BINARY SEARCH PROBLEM
class Solution {
public:
int pivot(vector& nums)
{
int n=nums.size();
int l=0;
int u=n-1;
while(l<=u)
{
int mid=l+(u-l)/2;
int next=(mid+1)%n;
int prev=(mid+n-1)%n;
if(nums[mid]<=nums[prev] && nums[mid]<=nums[next])
{
return mid;
}
else if(nums[mid]<=nums[u])
{
u=mid-1;
}
else if(nums[mid]>=nums[l])
{
l=mid+1;
}
}
return -1;
}
int bi_search(vector<int>& nums, int l,int u, int target)
{
while(l<=u)
{
int mid=l+(u-l)/2;
if(nums[mid]==target)
return mid;
else if(target>=nums[mid])
{
l=mid+1;
}
else
{
u=mid-1;
}
}
return -1;
}
int search(vector<int>& nums, int target) {
int pi=pivot(nums);
int ans1=bi_search(nums,0,pi-1,target);
int ans2=bi_search(nums,pi,nums.size()-1,target);
int res=max(ans1,ans2);
return res;
}
};
TC: O(log n)
SC: O(1)