-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathRotated Sorted Array.cpp
42 lines (41 loc) · 1.01 KB
/
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
class Solution {
public:
int search(vector<int>& nums, int target)
{
int n = nums.size();
int index = -1, left = 0, right = n-1;
while(left <= right)
{
int mid = left + (right - left) / 2;
if(mid > 0 && nums[mid] < nums[mid-1])
{
index = mid - 1;
break;
}
if(mid < n-1 && nums[mid] > nums[mid+1])
{
index = mid;
break;
}
if(nums[mid] > nums[right]) left = mid + 1;
else right = mid - 1;
}
left = 0, right = index;
while(left <= right)
{
int mid = left + (right - left) / 2;
if(nums[mid] == target) return mid;
else if(nums[mid] > target) right = mid-1;
else left = mid + 1;
}
left = index + 1, right = n - 1;
while(left <= right)
{
int mid = left + (right - left) / 2;
if(nums[mid] == target) return mid;
else if(nums[mid] > target) right = mid - 1;
else left = mid + 1;
}
return -1;
}
};