把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
示例 1:
输入:[3,4,5,1,2]
输出:1
示例 2:
输入:[2,2,2,0,1]
输出:0
注意:本题与主站 154 题相同:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/
解决方案
二分查找,利用递增排序数组旋转后的特性,可以将时间复杂度由O(n)减少到O(logn)。
一图胜千言:旋转数组的最小数字 – 旋转数组的最小数字 – 力扣(LeetCode)。
class Solution {
public int minArray(int[] numbers) {
int low = 0, high = numbers.length - 1;
while (low < high) {
int pivot = low + (high - low) / 2;
int number = numbers[pivot];
if (number < numbers[high]) {
high = pivot;
} else if (number > numbers[high]) {
low = pivot + 1;
} else {
high -= 1;
}
}
return numbers[low];
}
}
class Solution {
fun minArray(numbers: IntArray): Int {
var low = 0
var high = numbers.lastIndex
while (low < high) {
val pivot = low + (high - low) / 2
val number = numbers[pivot]
if (number < numbers[high]) {
high = pivot
} else if (number > numbers[high]) {
low = pivot + 1
} else {
high -= 1
}
}
return numbers[low]
}
}