旋转数组的最小数字
旋转数组的最小数字
题目描述:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
题目思路:
一、遍历
- 标记第一个元素为res
- 遍历数组找到第一个比res小的即为res
- 返回res
public int minArray(int[] numbers) {
//标记第一个数字
int res = numbers[0];
//遍历数组
for (int num : numbers) {
//查找到第一个比target小的数字
if (num < res){
res = num;
break;
}
}
return res;
}
二、二分查找
- 由于题目可知道,我们假设最右边的数字为x
- 那么最小值右边的值一定小于等于x
- 最小值左边的值一定大于等于x
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];
}
}

浙公网安备 33010602011771号