题目:
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.
解法:对于有序数组来说,折半查找的效率最高,但是这题的数组循环移了个位,也就变成了2个有序数组的拼接,当然我们一个一个的查找O(n)的效率,系统也能接受,但是还是不甘,仔细想想其实还是可以使用折半查找的。
Rotate之后的情况无非这两种
因此,查找low~mid-1的情况有:
1、A[mid]>A[high] && (target<A[mid] && target > A[low]))
2、A[mid]<A[high] && (target<A[mid]
3、A[mid]<A[high] && (target>A[low] && target > A[high])
其余情况查找mid+1~high(我这里省略了target和high,mid,low匹配的情况)
public class No32_SearchInRotatedSortedArray {
public static void main(String[] args){
// System.out.println(search(new int[]{1}, 1));
System.out.println(search(new int[]{1,2,3,4,5,6,7}, 5));
}
public static int search(int[] A, int target) {
return searchWithIndex(A, target, 0, A.length-1);
}
public static int searchWithIndex(int[] A, int target, int low, int high){
if(low <= high){
int mid = (high-low)/2 + low;
if(target == A[mid])
return mid;
if(target == A[low])
return low;
if(target == A[high])
return high;
if((A[mid]>A[high] && (target<A[mid] && target > A[low])) || (A[mid]<A[high] && (target<A[mid] || (target>A[low] && target > A[high]))))
return searchWithIndex(A, target, low, mid-1);
else
return searchWithIndex(A, target, mid+1, high);
}
return -1;
}
}