153 Find Minimum in Rotated Sorted Array 旋转数组的最小值

Posted lina2014

tags:

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

假设一个按照升序排列的有序数组从某未知的位置旋转。
(比如 0 1 2 4 5 6 7 可能变成 4 5 6 7 0 1 2)。
找到其中最小的元素。
你可以假设数组中不存在重复的元素。
详见:https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/

class Solution {
public:
    int findMin(vector<int>& nums) {
        int low=0;
        int high=nums.size()-1;
        int mid=0;
        while(nums[low]>=nums[high])
        {
            if(high-low==1)
            {
                mid=high;
                break;
            }
            mid=(low+high)/2;
            if(nums[low]==nums[mid]&&nums[mid]==nums[high])
            {
                int mn=nums[low];
                for(int i=low+1;i<=high;++i)
                {
                    if(nums[i]<mn)
                    {
                        mn=nums[i];
                    }
                }
                return mn;
            }
            else if(nums[low]<=nums[mid])
            {
                low=mid;
            }
            else if(nums[mid]<=nums[high])
            {
                high=mid;
            }
        }
        return nums[mid];
    }
};

 

以上是关于153 Find Minimum in Rotated Sorted Array 旋转数组的最小值的主要内容,如果未能解决你的问题,请参考以下文章