题目:
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在哪,自己画看看)。接下来就只需要按照这个特性继续写下去就好。以下是思路:
Take “4 5 6 7 0 1 2″ as an example. The mid entry is 7. We can compare it with the first entry. If the first entry is smaller than the mid entry, then the first half (from 4 to 7) must be in strictly increasing order. So we can compare target with the first entry and the mid entry, then we can decide if the target is in this half or not. If the first entry is larger than the mid entry, then the second half (fron 7 to 2) is in strictly increasing order. We can compare the target with them. Using this algorithm, every time we can throw half of the array.
代码如下:
1 public class Solution { 2 public int search(int[] A, int target) { 3 int left = 0; 4 int right = A.length - 1; 5 while (left <= right) { 6 int mid = (left + right) / 2; 7 if (A[mid] == target) 8 return mid; 9 if (A[left] <= A[mid]) { //左边sorted 10 if (target >= A[left] && target <= A[mid]) 11 right = mid - 1; 12 else //如果target比A[left]小,必然也比A[mid]小;如果target比A[mid]大,自然也比A[left]大 13 left = mid + 1; 14 } else { //右边sorted 15 if (target >= A[mid] && target <= A[right]) 16 left = mid + 1; 17 else 18 right = mid - 1; 19 } 20 } 21 return -1; 22 } 23 }
http://www.lifeincode.net/programming/leetcode-search-in-rotated-sorted-array-java/
The complexity is O(log n), which is similar to binary search.
Find the rotation pivot.
Solution from leetcode.com.
1 int FindSortedArrayRotation(int A[], int N) { 2 int L = 0; 3 int R = N - 1; 4 5 while (A[L] > A[R]) { 6 int M = L + (R - L) / 2; 7 if (A[M] > A[R]) 8 L = M + 1; 9 else 10 R = M; 11 } 12 return L; 13 }
For details: http://leetcode.com/2010/04/searching-element-in-rotated-array.html.
Reference:
http://www.lifeincode.net/programming/leetcode-search-in-rotated-sorted-array-java/
http://www.cnblogs.com/springfor/p/3858140.html
http://leetcode.com/2010/04/searching-element-in-rotated-array.html.