Suppose a sorted array 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.
分析:题目的意思是,原本有一个已经排好序的数组,比如0 1 2 3 4 5 6 7,现在把它任意旋转,变成4 5 6 7 0 1 2,先观察一下旋转后的数组,是部分有序的,那么就利用这一点,进行查找目标元素(找不到则返回-1)。
虽然数组不是整体有序的,但仍可以使用二分查找,使复杂度降为logN:
1、建立头指针first,尾指针end,计算中间指针medium,若first指向的元素小于medium指向的元素,则意味着左半边的数组元素是有序的,否则右半边的数组有序;
2、若左半边的数组有序,然后判断target是否大于first且小于medium,若是,则该target在左半边数组中,那么再写一个标准的二分查找的方法就可以了;若不是,则该target在右半边数组中,重复第一步。直到medium指向的元素等于target。找不到则返回-1.
Java解题:
public static int search(int[] nums, int target) {
if(nums==null||nums.length==0)
return -1;
return findnum(0, nums.length-1, target, nums);
}
public static int findnum(int first,int end,int target,int[] nums){
int medium = (first+end)/2;
if(target==nums[medium])
return medium;
if(medium==first){
if(target==nums[end])
return end;
return -1;
}
if(nums[first]<nums[medium]){
if(nums[first]<=target&&target<=nums[medium]){
return sortfind(first,medium,target,nums);
}
return findnum(medium+1,end,target,nums);
}
else{
if(nums[medium]<=target&&target<=nums[end]){
return sortfind(medium+1,end,target,nums);
}
return findnum(first,medium,target,nums);
}
}
public static int sortfind(int first, int end, int target, int[] nums) {
int medium=(first+end)/2;
if(target==nums[medium])
return medium;
if(medium==first){
if(target==nums[end])
return end;
return -1;
}
if(target<nums[medium])
return sortfind(first,medium,target,nums);
else
return sortfind(medium+1,end,target,nums);
}