美文网首页
Leetcode 精选之二分查找(寻找旋转排序数组中的最小值)

Leetcode 精选之二分查找(寻找旋转排序数组中的最小值)

作者: Kevin_小飞象 | 来源:发表于2020-03-30 21:22 被阅读0次

题目描述

假设按照升序排序的数组在预先未知的某个点上进行了旋转。

( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。

请找出其中最小的元素。

你可以假设数组中不存在重复元素。

示例 1:

输入: [3,4,5,1,2]
输出: 1

示例 2:

输入: [4,5,6,7,0,1,2]
输出: 0

题目链接:力扣

解题思路



public class Main {
    public static void main(String[] args) {
        int[] nums1 = {3,4,5,1,2};
        int[] nums2 = {4,5,6,7,0,1,2};
        
        System.out.println(findMin(nums1));
        System.out.println(findMin(nums2));
    }
    
    public static int findMin(int[] nums) {
        int l = 0, h = nums.length - 1;
        while (l < h) {
            int m = l + (h - l) / 2;
            if (nums[m] <= nums[h]) {
                h = m;
            } else {
                l = m + 1;
            }
        }
        return nums[l];
    }
}

测试结果

image.png

相关文章

网友评论

      本文标题:Leetcode 精选之二分查找(寻找旋转排序数组中的最小值)

      本文链接:https://www.haomeiwen.com/subject/jcubuhtx.html