**Leetcode 153. Find Minimum in Rotated Sorted Array

Posted Z-Pilgrim

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了**Leetcode 153. Find Minimum in Rotated Sorted Array相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/

面试最常见的题之一了

补充一些细节问题:

1)为什么不能根据mid和nums[0]来做二分(如果nums[mid] > nums[0] 在mid右边找)

2)为什么要mid对比右边界

对于1)很容易举出来反例,如果数组是递增的,在mid右边找自然是不对的

                特判nums[0]和nums[length-1]能特判递增情况

        2)递增是一种bad case

                非递增一个bad case   [4,5,6,7,0,1,2] ,由于数组本身最小值是在子数组的左边,当做完一轮二分之后,有可能子数组是递增的,这个时候,继续对比nums[l] 和nums[mid] 就会出问题

class Solution 
public:
    int findMin(vector<int>& nums) 
        int left = 0, right = nums.size() - 1;
        int mid = 0, en = right;
        while (left <= right) 
            mid = (left + right)/2;
            if (mid && nums[mid] < nums[mid-1]) return nums[mid];
            
            if (nums[mid] > nums[right]) 
                left = mid + 1;
             else 
                right = mid - 1;
            
        
        return nums[mid];
    
;

其他写法:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/48484/A-concise-solution-with-proof-in-the-comment

class Solution 
public:
    int findMin(vector<int> &num) 
        int low = 0, high = num.size() - 1;
        // loop invariant: 1. low < high
        //                 2. mid != high and thus A[mid] != A[high] (no duplicate exists)
        //                 3. minimum is between [low, high]
        // The proof that the loop will exit: after each iteration either the 'high' decreases
        // or the 'low' increases, so the interval [low, high] will always shrink.
        while (low < high) 
            auto mid = low + (high - low) / 2;
            if (num[mid] < num[high])
                // the mininum is in the left part
                high = mid;
            else if (num[mid] > num[high])
                // the mininum is in the right part
                low = mid + 1;
        

        return num[low];
    
;

以上是关于**Leetcode 153. Find Minimum in Rotated Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 153. Find Minimum in Rotated Sorted Array

LeetCode-153-Find Minimum in Rotated Sorted Array

LeetCode 153 Find Minimum in Rotated Sorted Array

153. Find Minimum in Rotated Sorted Array - LeetCode

**Leetcode 153. Find Minimum in Rotated Sorted Array

leetcode 153. Find Minimum in Rotated Sorted Array --------- java