https://leetcode.com/problems/search-in-rotated-sorted-array/description/原题链接
Suppose an array sorted in ascending order 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.
中文:
假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。
给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。
解题思路:
主要思想是二分查找,虽然是旋转的数组,但是还是满足,找到中间值mid之后,通过判断mid值是否大于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;
int mid;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (A[mid] == target) {
return mid;
}
if (A[start] < A[mid]) {
if (A[start] <= target && target <= A[mid]) {
end = mid;
} else {
start = mid;
}
} else {
if (A[mid] <= target && target <= A[end]) {
start = mid;
} else {
end = mid;
}
}
}
if (A[start] == target) {
return start;
}
if (A[end] == target) {
return end;
}
return -1;
}
}