forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search-in-rotated-sorted-array.cpp
72 lines (66 loc) · 1.78 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
61
62
63
64
65
66
67
68
69
70
71
72
// Time: O(logn)
// Space: O(1)
class Solution {
/**
* param A : an integer ratated sorted array
* param target : an integer to be searched
* return : an integer
*/
public:
int search(vector<int> &A, int target) {
int left = 0;
int right = A.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (A[mid] == target) {
return mid;
}
else if (A[left] <= A[mid]) {
if (A[left] <= target && target < A[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (A[mid] < target && target <= A[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
};
class Solution2 {
/**
* param A : an integer ratated sorted array
* param target : an integer to be searched
* return : an integer
*/
public:
int search(vector<int> &A, int target) {
int left = 0;
int right = A.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (A[mid] == target) {
return mid;
}
else if (A[left] <= A[mid]) {
if (A[left] <= target && target < A[mid]) {
right = mid;
} else {
left = mid + 1;
}
} else {
if (A[mid] < target && target <= A[right - 1]) {
left = mid + 1;
} else {
right = mid;
}
}
}
return -1;
}
};