leetcode 11:旋转数组的最小数字
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
给你一个可能存在 重复 元素值的数组 numbers
,它原来是一个升序排列的数组,并按上述情形进行了一次旋转。请返回旋转数组的最小元素。例如,数组 [3,4,5,1,2]
为 [1,2,3,4,5]
的一次旋转,该数组的最小值为 1。
注意,数组 [a[0], a[1], a[2], ..., a[n-1]]
旋转一次 的结果为数组 [a[n-1], a[0], a[1], a[2], ..., a[n-2]]
。
示例 1:
输入:numbers = [3,4,5,1,2]
输出:1
示例 2:
输入:numbers = [2,2,2,0,1]
输出:0
提示:
n == numbers.length
1 <= n <= 5000
-5000 <= numbers[i] <= 5000
numbers
原来是一个升序排序的数组,并进行了1
至n
次旋转
注意:本题与主站 154 题相同:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/
Related Topics
数组
二分查找
思路:二分查找
官方参考连接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/solution/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-by-leetcode-s/
class Solution {
public int minArray(int[] numbers) {
int min = Integer.MAX_VALUE;
int start = 0;
int end = numbers.length-1;
while (start < end){
int mid = start + (end-start)/2;
//最小值一定在[start,mid]范围
if(numbers[mid] < numbers[end]){
end = mid;
//最小值一定在[mid+1,end]
}else if(numbers[mid] > numbers[end]){
start = mid +1;
//此时最小值可能在mid的左侧或者右侧
//但是肯定可以忽略掉最右边的end,因为他们两相等
}else{
end -= 1;
}
}
return numbers[start];
}
}