描述
假设有一个排序的按未知的旋转轴旋转的数组(比如0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2),给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。你可以假设数组中不存在重复的元素。
样例
给出[4, 5, 1, 2, 3]和target=1,返回 2
给出[4, 5, 1, 2, 3]和target=0,返回 -1
挑战
O(logN) time
思路
同在循环数组中找到最小值相似,数组分为两部分,以A[start](A[end]同一点)为分界点,判断mid在哪个范围,然后用经典二分法继续查找,经典二分法查找时应注意范围的书写 and 对数组进行查找要注意写异常情况。最后结果的end和start顺序可以调换
代码
public class Solution {
public int search(int[] A, int target) {
if (A == null || A.length == 0) {
return -1;
}
int start = 0;
int end = A.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] == target) {
return mid;
}
// 通过 target 和 A[start] 比较,判断区间到底在哪一个分割区
if (A[start] < A[mid]) {
if (A[start] <= target && A[mid] >= target) {
end = mid;
}
else {
start = mid;
}
}
if (A[start] > A[mid]) {
if (A[mid] <= target && A[end] >= target) {
start = mid;
}
else {
end = mid;
}
}
}
if (A[start] == target) {
return start;
}
if (A[end] == target) {
return end;
}
return -1;
}
}
- 两次二分
public class Solution {
/*
* @param A: an integer rotated sorted array
* @param target: an integer to be searched
* @return: an integer
*/
public int search(int[] A, int target) {
if (A == null || A.length == 0) {
return -1;
}
int start = 0;
int end = A.length - 1;
int target1 = A[A.length - 1];
int index = findIndex(A, target1);
if (index > 0 && target <= A[index - 1] && target >= A[start]) {
start = 0;
end = index - 1;
return findTarget(start, end, A, target);
}
if (target >= A[index] && target <= A[end]) {
start = index;
end = A.length - 1;
return findTarget(start, end, A, target);
}
return -1;
}
private int findIndex(int[] A, int target) {
int start = 0;
int end = A.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (A[mid] > target) {
start = mid;
} else {
end = mid;
}
}
if (A[start] > target) {
return end;
} else {
return start;
}
}
private int findTarget(int start, int end, int[] A, int target) {
if (start >= end) {
return start;
}
int l = start;
int r = end;
while (l + 1 < r) {
int mid = l + (r - l) / 2;
if (A[mid] == target) {
return mid;
}
if (A[mid] < target) {
l = mid;
} else {
r = mid;
}
}
if (A[r] == target) {
return r;
}
if (A[l] == target) {
return l;
}
return -1;
}
}