-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode33.cpp
65 lines (64 loc) · 2.04 KB
/
leetcode33.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
// beats over 69.9% of submission
class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.size() == 1) {
if(target == nums[0]) return 0;
else return -1;
}
// find rotate pivot
int rotate = -1;
for(int i = 1; i < nums.size(); ++i) {
if(nums[i] < nums[i - 1]) rotate = i;
}
int start = 0, end = nums.size() - 1, mid = 0;
if(rotate != -1) {
// if rotated, divide by rotate pivot
if(nums[rotate] == target) return rotate;
if(target > nums[rotate - 1] || target < nums[rotate]) return -1;
if(target <= *(--nums.end())) start = rotate;
else if(target >= *(nums.begin())) end = rotate - 1;
}
// BS
while(start <= end) {
mid = start + ((end - start) >> 1);
if(nums[mid] == target) return mid;
if(nums[mid] < target) start = mid + 1;
else end = mid - 1;
}
return -1;
}
};
// beats over 96.5% of submission
class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.size() == 1) {
if(target == nums[0]) return 0;
else return -1;
}
int start = 0, end = nums.size() - 1, mid = 0;
while(start <= end) {
mid = start + ((end - start) >> 1);
if(nums[mid] == target) return mid;
if(nums[mid] >= nums[start]) {
// left is in order
if(target < nums[mid] && target >= nums[start]) {
// target is in left section
end = mid - 1;
}else {
start = mid + 1;
}
}else {
// right is in order
if(target > nums[mid] && target <= nums[end]) {
// target is in right section
start = mid + 1;
}else {
end = mid - 1;
}
}
}
return -1;
}
};