forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
search-in-rotated-sorted-array-ii.cpp
48 lines (42 loc) · 1.37 KB
/
search-in-rotated-sorted-array-ii.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
// Time: O(logn)
// Space: O(1)
class Solution {
public:
bool search(vector<int> &nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return true;
} else if (nums[mid] == nums[left]) {
++left;
} else if ((nums[mid] > nums[left] && nums[left] <= target && target < nums[mid]) ||
(nums[mid] < nums[left] && !(nums[mid] < target && target <= nums[right]))) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return false;
}
};
class Solution2 {
public:
bool search(vector<int> &nums, int target) {
int left = 0, right = nums.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return true;
} else if (nums[mid] == nums[left]) {
++left;
} else if ((nums[left] <= nums[mid] && nums[left] <= target && target < nums[mid]) ||
(nums[left] > nums[mid] && !(nums[mid] < target && target <= nums[right - 1]))) {
right = mid;
} else {
left = mid + 1;
}
}
return false;
}
};