leetcode链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
示例 1:
输入:[3,4,5,1,2] 输出:1示例 2:
输入:[2,2,2,0,1] 输出:0
解题思路:因为数组在旋转之前是有序的,因此可以采用二分查找的算法,
当 numbers[m] > numbers[j]时: mmm 一定在 左排序数组 中,即旋转点 xxx 一定在 [m+1,j][m + 1, j][m+1,j] 闭区间内,因此执行 i=m+1i = m + 1i=m+1;
当 numbers[m] < numbers[j] 时: mmm 一定在 右排序数组 中,即旋转点 xxx 一定在[i,m][i, m][i,m] 闭区间内,因此执行 j=mj = mj=m;
当 numbers[m] == numbers[j] 时: 无法判断 mmm 在哪个排序数组中,即无法判断旋转点 xxx 在 [i,m][i, m][i,m] 还是 [m+1,j][m + 1, j][m+1,j] 区间中。解决方案: 执行 j=j−1j = j - 1j=j−1 缩小判断范围。也就是去掉一个重复的元素。
class Solution {
public int minArray(int[] numbers) {
if(numbers.length == 0){
return 0;
}
int start = 0,end = numbers.length-1;
while(start<end){
int mid = (start+end)/2;
if(numbers[mid]<numbers[end]){
end = mid;
}else if(numbers[mid]>numbers[end]){
start = mid+1;
}else{
end--;
}
}
return numbers[start];
}
}