1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public int search(int[] nums, int target) { int n = nums.length, idx = 0; for (int i = 0; i < n - 1; i++) { if (nums[i] > nums[i + 1]) { idx = i; break; } } int ans = binarySearch(nums, 0, idx, target); if (ans != -1) return ans; if (idx + 1 < n) ans = binarySearch(nums, idx + 1, n - 1, target); return ans; }
private int binarySearch(int[] nums, int left, int right, int target) { while (left < right) { int mid = left + right >> 1; if (nums[mid] >= target) right = mid; else left = mid + 1; } return nums[left] == target ? left : -1; } }
|