LeetCode 153: Find Minimum in Rotated Sorted Array

问题描述

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).

Find the minimum element.

You may assume no duplicate exists in the array.

Example 1:

Input: [3,4,5,1,2]
Output: 1
Example 2:

Input: [4,5,6,7,0,1,2]
Output: 0

思路

二分法

java实现

class Solution {
    public int findMin(int[] nums) {
        if(nums==null || nums.length==0)
            return 0;
        int start=0;
        int end=nums.length-1;
        //说明数组递增有序
        if(nums[start]<nums[end])
            return nums[start];
        while (start+1<end){
            int mid=start+(end-start)/2;
            if(nums[mid]>nums[start])
                start=mid;//中间位置值大于起始位置值,说明前半段递增,最小的数字在后半段
            else//中间位置值小于起始位置值,说明前半段递减,最小的数字在前半段
                end=mid;
        }
        return Math.min(nums[start],nums[end]);

    }
}
发布了172 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44135282/article/details/103500353
今日推荐