[Link] https://leetcode.com/problems/search-in-rotated-sorted-array/
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
class Solution {
public int search(int[] nums, int target) {
int l = 0, r = nums.length - 1, mid;
while(l <= r) {
mid = (l + r) / 2;
if(nums[mid] == target) return mid;
if(nums[l] < nums[r]) { // 1 3 4 5
if(nums[mid] < target) l = mid + 1;
else r = mid - 1;
} else { //8 9 10 1 2 3 4 5
int left = l, right = r, m;
while(left <= right) {
m = (left + right) / 2;
if(left == m) {
if(left < nums.length - 1 && nums[left] < nums[left + 1]) left++;
break;
}
if(nums[m] < nums[left]) right = m - 1;
else left = m;
}
if(target >= nums[l]) {
int lt = l, rt = left, mt;
while(lt <= rt) {
mt = (lt + rt) / 2;
if(nums[mt] == target) return mt;
if(nums[mt] > target) rt = mt - 1;
else lt = mt + 1;
}
return - 1;
} else {
int lt = left + 1, rt = r, mt;
while(lt <= rt) {
mt = (lt + rt) / 2;
if(nums[mt] == target) return mt;
if(nums[mt] > target) rt = mt - 1;
else lt = mt + 1;
}
return -1;
}
}
}
return -1;
}
}