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.
主题思想: 这道题的关键是利用原先是有序数组,经过变换过来的,如果能够知道变换pivot 元素在原数组的下标,以及要查找target 在原数组的下标,很容易经过数学换算,一步得出target 在当前(由原数组变换后得到) 数组的下标。 而在有序数组中查找下边,可以log N 查找
所以要分析,已知pivot 元素在原数组,和target在原数组下标,如何换算得到target 在当前数组的下边。
很容易有个分析思路就是: pivot 下标和target 下边之间关系有三种:
1. 等于,这是pivot 变换后成为当前数组第一个元素,下标为0
2. target下标小于pivot 下标 ,则旋转后 n-pivot下标+target下标
3. target 下标大于pivot 下标,则旋转后,target下标-pivot下标
代码:
class Solution {
public int search(int[] nums, int target) {
if(nums==null||nums.length==0) return -1;
int pivot=nums[0];
Arrays.sort(nums);
// find pivot and find the target
int targetIndex=find(nums,target);
if(targetIndex==-1) return -1;
int pivotIndex=find(nums,pivot);
if(pivotIndex==targetIndex) return 0;
else if(pivotIndex<targetIndex) return targetIndex-pivotIndex;
else return nums.length-pivotIndex+targetIndex;
}
public int find(int [] nums,int target){
int low=0;
int hi=nums.length-1;
while(low<=hi){
int mid=low+(hi-low)/2;
if(target<nums[mid]){
hi=mid-1;
}else if(target>nums[mid]){
low=mid+1;
}else{
return mid;
}
}
return -1;
}
}