-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathsearch-in-rotated-sorted-array.cc
More file actions
48 lines (46 loc) · 971 Bytes
/
search-in-rotated-sorted-array.cc
File metadata and controls
48 lines (46 loc) · 971 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
45
46
47
48
// Search in Rotated Sorted Array
class Solution {
public:
int search(vector<int> &a, int target) {
int n = a.size(), l = 0, h = n;
while (l < h) {
int m = l+h >> 1;
if (a[m] < target) {
if (target < a[l] || a[l] < a[m])
l = m+1;
else
h = m;
} else if (a[m] > target) {
if (a[l] <= target || a[l] > a[m])
h = m;
else
l = m+1;
} else
return m;
}
return -1;
}
};
///
class Solution {
public:
int search(vector<int> &a, int target) {
int n = a.size(), l = 0, h = n;
while (l < h) {
int m = l+h >> 1;
if (a[m] == target) return m;
if (a[l] < a[m]) {
if (a[l] <= target && target < a[m])
h = m;
else
l = m+1;
} else {
if (a[m] < target && target <= a[h-1])
l = m+1;
else
h = m;
}
}
return l < n && a[l] == target ? l : -1;
}
};