題目:
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.
題解:
這道題是一道常見的二分查詢法的變體題。
要解決這道題,需要明確rotated sorted array的特性,那麼就是至少有一側是排好序的(無論pivot在哪,自己畫看看)。接下來就只需要按照這個特性繼續寫下去就好。以下就以虛擬碼方法來說明:
- 如果target比A[mid]值要小
- 如果A[mid]右邊有序(A[mid]<A[high])
- 那麼target肯定不在右邊(target比右邊的都得小),在左邊找
- 如果A[mid]左邊有序
- 那麼比較target和A[low],如果target比A[low]還要小,證明target不在這一區,去右邊找;反之,左邊找。
- 如果target比A[mid]值要大
- 如果A[mid]左邊有序(A[mid]>A[low])
- 那麼target肯定不在左邊(target比左邊的都得大),在右邊找
- 如果A[mid]右邊有序
- 那麼比較target和A[high],如果target比A[high]還要大,證明target不在這一區,去左邊找;反之,右邊找。
以上實現程式碼如下所示:
1 public int search(int [] A,int target){
2 if(A==null||A.length==0)
3 return -1;
4
5 int low = 0;
6 int high = A.length-1;
7
8 while(low <= high){
9 int mid = (low + high)/2;
10 if(target < A[mid]){
11 if(A[mid]<A[high])//right side is sorted
12 high = mid - 1;//target must in left side
13 else
14 if(target<A[low])//target<A[mid]&&target<A[low]==>means,target cannot be in [low,mid] since this side is sorted
15 low = mid + 1;
16 else
17 high = mid - 1;
18 }else if(target > A[mid]){
19 if(A[low]<A[mid])//left side is sorted
20 low = mid + 1;//target must in right side
21 else
22 if(target>A[high])//right side is sorted. If target>A[high] means target is not in this side
23 high = mid - 1;
24 else
25 low = mid + 1;
26 }else
27 return mid;
28 }
29
30 return -1;
31 }
2 if(A==null||A.length==0)
3 return -1;
4
5 int low = 0;
6 int high = A.length-1;
7
8 while(low <= high){
9 int mid = (low + high)/2;
10 if(target < A[mid]){
11 if(A[mid]<A[high])//right side is sorted
12 high = mid - 1;//target must in left side
13 else
14 if(target<A[low])//target<A[mid]&&target<A[low]==>means,target cannot be in [low,mid] since this side is sorted
15 low = mid + 1;
16 else
17 high = mid - 1;
18 }else if(target > A[mid]){
19 if(A[low]<A[mid])//left side is sorted
20 low = mid + 1;//target must in right side
21 else
22 if(target>A[high])//right side is sorted. If target>A[high] means target is not in this side
23 high = mid - 1;
24 else
25 low = mid + 1;
26 }else
27 return mid;
28 }
29
30 return -1;
31 }
Reference:http://www.cnblogs.com/ider/archive/2012/04/01/binary_search.html