把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
方法一:依题意 可以使用双指针遍历 找出第一次降序的位置 即为所求
当 prev > cur 此时的cur即为该旋转数组的最小值
class Solution {
public int minArray(int[] numbers) {
int i = 0;
for(i=0 ; i < numbers.length-1; i++){
if(numbers[i]>numbers[i+1])
return numbers[i+1];
}
return numbers[0];
}
}
方法二:
class Solution {
public int minArray(int[] numbers) {
int low = 0;
int high = numbers.length - 1;
while (low < high) {
int pivot = low + (high - low) / 2;
if (numbers[pivot] < numbers[high]) {
high = pivot;
} else if (numbers[pivot] > numbers[high]) {
low = pivot + 1;
} else {
high -= 1;
}
}
return numbers[low];
}
}