forked from anshuman8800/Interivew-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearchInRotatedSortedArray.cpp
More file actions
44 lines (43 loc) · 943 Bytes
/
searchInRotatedSortedArray.cpp
File metadata and controls
44 lines (43 loc) · 943 Bytes
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
class Solution {
public:
int search(vector<int>& nums, int target) {
int l=0, n=nums.size(), h=n-1, mid=l+(h-l)/2, in=0;
while(l<=h)
{
mid=l+(h-l)/2;
int x=(mid-1+n)%n, y=(mid+1)%n;
if(nums[mid]<nums[x] && nums[mid]<nums[y])
{
in=mid;
break;
}
else if(nums[mid]>=nums[n-1])
{
l=mid+1;
}
else
{
h=mid-1;
}
}
if(target>nums[n-1])
{
l=0, h=in-1;
}
else
{
l=in, h=n-1;
}
while(l<=h)
{
mid=l+(h-l)/2;
if(nums[mid]==target)
return mid;
else if(nums[mid]<target)
l=mid+1;
else
h=mid-1;
}
return -1;
}
};