Find Minimum in Rotated Sorted Array,Find Minimum in Rotated Sorted ArrayII

一: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 low  = 0;
        int high = nums.size()-1;
        
        while(low<=high){
            
            int mid = low + (high-low)/2;
            if(nums[mid] == nums[high]){
                high--;
            }else if(nums[mid] > nums[high]){
                low = mid+1;
            }else{
                high = mid;
            }
        }
        
        return nums[low];
    }
};

 

二:Find Minimum in Rotated Sorted ArrayII

与一不同的是,其允许有重复元素

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

 

posted @ 2015-11-12 14:55  zengzy  阅读(159)  评论(0编辑  收藏  举报
levels of contents