classSolution{int[] nums;int target;publicintfind_rotate_index(int left,int right){if(nums[left]< nums[right])return0;while(left <= right){int pivot =(left + right)/2;if(nums[pivot]> nums[pivot +1])return pivot +1;else{if(nums[pivot]< nums[left])
right = pivot -1;else
left = pivot +1;}}return0;}publicintsearch(int left,int right){/*
Binary search
*/while(left <= right){int pivot =(left + right)/2;if(nums[pivot]== target)return pivot;else{if(target < nums[pivot])
right = pivot -1;else
left = pivot +1;}}return-1;}publicintsearch(int[] nums,int target){this.nums = nums;this.target = target;int n = nums.length;if(n ==0)return-1;if(n ==1)returnthis.nums[0]== target ?0:-1;int rotate_index =find_rotate_index(0, n -1);// if target is the smallest elementif(nums[rotate_index]== target)return rotate_index;// if array is not rotated, search in the entire arrayif(rotate_index ==0)returnsearch(0, n -1);if(target < nums[0])// search in the right sidereturnsearch(rotate_index, n -1);// search in the left sidereturnsearch(0, rotate_index);}}
作者:LeetCode
链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array/solution/sou-suo-xuan-zhuan-pai-xu-shu-zu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。