When there is a pivot, you take a mid, and two parts are obtained: one sorted part and the other half. Binary search inside the sorted part.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Solution { public int search(int[] nums, int target) { if (nums.length == 0) return -1; int left = 0, right = nums.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (nums[mid] == target) return mid; else if (nums[mid] < nums[right]) { if (nums[mid] < target && target <= nums[right]) left = mid+1; else right = mid-1; } else { if (nums[mid] > target && nums[left] <= target) right = mid-1; else left = mid + 1; } } return -1; } }
nums[mid] < nums[right]: a prev comparison before formal nums[mid] < target and nums[mid] > target