-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy path81-search-in-rotated-sorted-array-ii.cpp
More file actions
37 lines (34 loc) · 1.1 KB
/
81-search-in-rotated-sorted-array-ii.cpp
File metadata and controls
37 lines (34 loc) · 1.1 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
class Solution {
public:
bool search(vector<int>& nums, int target) {
int n = nums.size();
if (n == 0) return false;
int left = 0;
int right = n - 1;
int mid, midNum, leftNum, rightNum;
while (left <= right) {
mid = (left + right) / 2;
midNum = nums[mid];
leftNum = nums[left];
rightNum = nums[right];
if (midNum == target) {
return true;
} else if (leftNum < midNum) { // left array is sorted
if (target >= leftNum && target <= midNum) {
right = mid - 1;
} else {
left = mid + 1;
}
} else if (leftNum > midNum) { // right array is sorted
if (target >= midNum && target <= rightNum) {
left = mid + 1;
} else {
right = mid - 1;
}
} else {
left++;
}
}
return false;
}
};