Find Minumu in Rotated Sorted Ar

2020-03-19  本文已影响0人  默写年华Antifragile

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

对于一个有序数组,将其元素以某一个元素为轴进行旋转,比如[0,1,2,3,4,5,6,7]可能会变成[4,5,6,7,0,1,2,3]
求这个经过旋转的数组的最小值,这里假设数组中没有重复值

二分查找

class Solution {
public:
    int findMin(vector<int>& nums) {
        int lo = 0, hi = nums.size()-1;
        while(lo < hi)
        {
            int mi = (lo + hi)>>1;
            if(nums[mi] < nums[hi])
                hi = mi;
            else
                lo = mi+1;
        }
        return nums[lo];
    }
};

时间复杂度 O(logN)


求这样一个数组的最大值

class Solution {
public:
    int findMin(vector<int>& nums) {
        int lo = 0, hi = nums.size()-1;
        while(lo < hi)
        {
            int mi = (lo + hi)>>1;
            if(nums[mi] < nums[hi])
                hi = mi-1;
            else
                lo = mi;
        }
        return nums[lo];
    }
};


相关问题,如果数组中存在相同的元素 https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii

上一篇下一篇

猜你喜欢

热点阅读