-
Notifications
You must be signed in to change notification settings - Fork 0
/
33
61 lines (60 loc) · 1.94 KB
/
33
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
class Solution {
public:
int search(vector<int>& nums, int target) {
if(nums.size() < 1)
return -1;
if(nums.size() < 4){
for(int i = 0; i < nums.size(); i ++)
if (nums[i] == target)
return i;
return -1;
}
if(nums[0] == target)
return 0;
if(nums.back() == target)
return nums.size() - 1;
int low,high,mid;
int l = nums[0], r = nums.back();
if(l<r){
for(low = 0, high = nums.size() - 1, mid = high / 2; low < high - 1; mid = (low+high) / 2){
if(nums[mid] > target)
high = mid;
else if(nums[mid] < target)
low = mid;
else
return mid;
}
}
else{
if(target > r){
for(low = 0, high = nums.size() - 1, mid = high / 2; low < high - 1; mid = (low+high) / 2){
if(nums[mid] > target)
high = mid;
else if(nums[mid] < target && nums[mid] > r)
low = mid;
else if(nums[mid] < target)
high = mid;
else
return mid;
}
}
else{
for(low = 0, high = nums.size() - 1, mid = high / 2; low < high - 1; mid = (low+high) / 2){
if(nums[mid] < target)
low = mid;
else if(nums[mid] > target && nums[mid] < l)
high = mid;
else if(nums[mid] > target)
low = mid;
else
return mid;
}
}
}
if(nums[low] == target)
return low;
if(nums[high] == target)
return high;
return -1;
}
};