leetcode.153. Find Minimum in Rotated Sorted Array

Suppose a sorted array 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.

思路一:

class Solution {
public:
    int findMin(vector<int>& nums) {
        int begin = 0;
        int end = nums.size()-1;
        while(begin<=end)
        {
            int mid = begin + (end-begin)/2;
            if(nums[mid]==nums[begin])
               return min(nums[mid],nums[end]);
               
                       
            else if(nums[mid]<nums[begin])
                  end = mid;
               
            else if(nums[mid]>nums[begin])
                if(nums[mid]>nums[end])
                   begin = mid;
                else   
                    return nums[begin];
          
        }
        return -1;
    }
    
};

思路二:

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


你可能感兴趣的:(leetcode.153. Find Minimum in Rotated Sorted Array)