Search in Rotated Sorted Array
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.
SOLUTION 1:
使用九章算法经典递归模板:
while (l < r - 1) 可以避免mid与left重合的现象。
其实和一般的二分法搜索没有太多区别。
问题是我们每次要找出正常排序的部分,你只需要比较mid, left,如果它们是正序,就代表左边是
正常排序,而右边存在断开的情况,也就是因为Rotated发生不正常序列。
例如:
4567012 如果我们取mid为7,则左边是正常序列,而右边7012不正常。
然后 我们再将target与正常排序的这边进行比较,如果target在左边,就丢弃右边,反之,丢弃
左边。一次我们可以扔掉一半。和二分搜索一样快。
public class Solution {
public int search(int[] A, int target) {
if (A == null || A.length == 0) {
return -1;
} int l = 0;
int r = A.length - 1; while (l < r - 1) {
int mid = l + (r - l) / 2; if (A[mid] == target) {
return mid;
} // left side is sorted.
// BUG 1: if don't use >= , and use L < r in while loop, than there is some problem.
if (A[mid] > A[l]) {
if (target > A[mid] || target < A[l]) {
// move to right;
l = mid + 1;
} else {
r = mid - 1;
}
} else {
if (target < A[mid] || target > A[r]) {
// move to left;
r = mid - 1;
} else {
l = mid + 1;
}
}
} if (A[l] == target) {
return l;
} else if (A[r] == target) {
return r;
} return -1;
}
}
SOLUTION 2:
注意,如果while 循环使用l <= r来卡,则mid有可能会靠到l这这来,所以当判断是否有序时,我们必须使用<=
总之,这份代码就不需要最后再判断l,r的值。
public int search(int[] A, int target) {
if (A == null || A.length == 0) {
return -1;
} int l = 0;
int r = A.length - 1; while (l <= r) {
int mid = l + (r - l) / 2; if (A[mid] == target) {
return mid;
} // left side is sorted.
// BUG 1: if don't use >= , and use L < r in while loop, than there is some problem.
if (A[mid] >= A[l]) {
if (target > A[mid] || target < A[l]) {
// move to right;
l = mid + 1;
} else {
r = mid - 1;
}
} else {
if (target < A[mid] || target > A[r]) {
// move to left;
r = mid - 1;
} else {
l = mid + 1;
}
}
} return -1;
}