Loading

【leetcode】153. Find Minimum in Rotated Sorted Array

Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
  • [4,5,6,7,0,1,2] if it was rotated 4 times.
  • [0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
 
class Solution {
public:
    int findMin(vector<int>& nums) {
        
        //O(logn 的时间复杂度 感觉是二分法的检索方式) left>right 的话 最小值就在这里面 这样二分检索
        //二分检索 中间的边界比较麻烦
        int n=nums.size();
        if(nums[0]<=nums[n-1]) return nums[0];
        int left=0,right=n-1;
        while(left<right-1)
        {
            int mid=(left+right)/2;
            if(nums[left]>nums[mid])
            {
                //left=left;
                right=mid;
            }
            else if(nums[mid]>nums[right])
            {
                left=mid;
                //right=right
            }
            else if(nums[left]==nums[mid])
            {
                left=mid+1;
            }
            else if(nums[right]==nums[mid])
            {
                right=mid-1;
            }
        }
        return min(nums[right],nums[left]);
        
    }
};

 

posted @ 2021-11-19 21:44  aalanwyr  阅读(33)  评论(0编辑  收藏  举报