-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInRotatedSortedArray.cpp
More file actions
53 lines (53 loc) · 1.27 KB
/
SearchInRotatedSortedArray.cpp
File metadata and controls
53 lines (53 loc) · 1.27 KB
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
class Solution {
public:
int search(vector<int>& nums, int target) {
int l = 0;
int r = nums.size() - 1;
while (l < r)
{
int m = (l + r) / 2;
if (nums[m] == target)
{
return m;
}
else if (nums[l] < nums[r])
{
if (nums[m] < target)
{
l = m + 1;
}
else
{
r = m - 1;
}
}
else
{
if (nums[m] >= nums[l])
{
if (nums[m] < target || nums[l] > target)
{
l = m + 1;
}
else
{
r = m - 1;
}
}
else
{
if (nums[m] > target || target > nums[r])
{
r = m - 1;
}
else
{
l = m + 1;
}
}
}
}
if (l == r && nums[l] == target) return l;
return -1;
}
};