旋转数组的最小数字

旋转数组的最小数字

题目描述:

把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。

题目思路:

一、遍历

  1. 标记第一个元素为res
  2. 遍历数组找到第一个比res小的即为res
  3. 返回res
public int minArray(int[] numbers) {
         //标记第一个数字
        int res = numbers[0];
        //遍历数组
        for (int num : numbers) {
            //查找到第一个比target小的数字
            if (num < res){
                res = num;
                break;
            }
        }
        return res;
    }

二、二分查找

  1. 由于题目可知道,我们假设最右边的数字为x
  2. 那么最小值右边的值一定小于等于x
  3. 最小值左边的值一定大于等于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];
    }
}
posted @ 2020-08-03 13:52  杨小星儿  阅读(105)  评论(0)    收藏  举报