Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
1 public class Solution { 2 public int search(int[] nums, int target) { 3 int low = 0, high = nums.length - 1; 4 while (low <= high) { 5 int mid = low + (high - low) / 2; 6 if (nums[mid] == target) return mid; 7 8 if (nums[mid] > target) { 9 if (nums[mid] > nums[high] && nums[high] >= target) 10 low = mid + 1; 11 else 12 high = mid - 1; 13 } else { 14 if (nums[mid] < nums[high] && nums[high] < target) 15 high = mid - 1; 16 else 17 low = mid + 1; 18 } 19 } 20 21 return -1; 22 } 23 }