问题描述
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e.,0 1 2 4 5 6 7might become4 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.
问题分析
这道题暴力求解也是可以的,但是正确的做法是找出分界点,对左右两边进行二分查找,这样的速度会比较快
代码实现
public int search(int[] A, int target) {
int position = 0;
for (int i = 1; i < A.length; i++) {
if (A[i] < A[i - 1]) {
position = i - 1;
}
}
int low = 0;
int high = position;
while (low <= high) {
int mid = (low + high) / 2;
if (A[mid] == target) return mid;
else if (A[mid] > target) high = mid - 1;
else if (A[mid] < target) low = mid + 1;
}
low = position + 1;
high = A.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (A[mid] == target) return mid;
else if (A[mid] > target) high = mid - 1;
else if (A[mid] < target) low = mid + 1;
}
return -1;
}
网友评论