forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
search-in-rotated-sorted-array.cpp
44 lines (38 loc) · 1.22 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
// Time: O(logn)
// Space: O(1)
class Solution {
public:
int 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 mid;
} 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 -1;
}
};
class Solution2 {
public:
int 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 mid;
} 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 -1;
}
};