|
1 | 1 | class Solution {
|
2 |
| - |
3 | 2 | public int search(int[] nums, int target) {
|
4 |
| - int minIndex = minIndex(nums); |
5 |
| - int leftSearch = binarySearch(nums, 0, minIndex - 1, target); |
6 |
| - int rightSearch = binarySearch(nums, minIndex, nums.length - 1, target); |
7 |
| - if (leftSearch != -1) { |
8 |
| - return leftSearch; |
9 |
| - } else if (rightSearch != -1) { |
10 |
| - return rightSearch; |
11 |
| - } else { |
12 |
| - return -1; |
13 |
| - } |
14 |
| - } |
15 | 3 |
|
16 |
| - public int minIndex(int[] nums) { |
17 |
| - int start = 0; |
18 |
| - int end = nums.length - 1; |
19 |
| - while (start <= end) { |
20 |
| - int mid = start + (end - start) / 2; |
21 |
| - int prev = (mid - 1 + nums.length) % nums.length; |
22 |
| - int next = (mid + 1) % nums.length; |
23 |
| - if (nums[mid] <= nums[prev] && nums[mid] <= nums[next]) { |
24 |
| - return mid; |
25 |
| - } else if (nums[mid] <= nums[end]) { |
26 |
| - end = mid - 1; |
27 |
| - } else if (nums[mid] >= nums[start]) { |
28 |
| - start = mid + 1; |
29 |
| - } |
30 |
| - } |
31 |
| - return -1; |
32 |
| - } |
| 4 | + int l = 0; |
| 5 | + int r = nums.length - 1; |
| 6 | + |
| 7 | + while(l<=r){ |
| 8 | + |
| 9 | + int mid = (l+r)/2; |
33 | 10 |
|
34 |
| - public int binarySearch(int[] nums, int start, int end, int target) { |
35 |
| - while (start <= end) { |
36 |
| - int mid = start + (end - start) / 2; |
37 |
| - if (nums[mid] == target) { |
| 11 | + if(nums[mid] == target){ |
38 | 12 | return mid;
|
39 |
| - } else if (nums[mid] < target) { |
40 |
| - start = mid + 1; |
41 |
| - } else { |
42 |
| - end = mid - 1; |
43 | 13 | }
|
| 14 | + //left sorted |
| 15 | + if(nums[l]<=nums[mid]){ |
| 16 | + if(target > nums[mid] || target < nums[l]){ |
| 17 | + l = mid + 1; |
| 18 | + }else{ |
| 19 | + r = mid - 1; |
| 20 | + } |
| 21 | + }else{//right sorted |
| 22 | + if(target < nums[mid] || target > nums [r]){ |
| 23 | + r = mid - 1; |
| 24 | + }else{ |
| 25 | + l = mid + 1; |
| 26 | + } |
| 27 | + } |
| 28 | + |
44 | 29 | }
|
| 30 | + |
45 | 31 | return -1;
|
46 | 32 | }
|
47 | 33 | }
|
0 commit comments