153. Find Minimum in Rotated Sorted Array

153. Find Minimum in Rotated Sorted Array

My Submissions
Question
Total Accepted: 73048  Total Submissions: 209952  Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
  Array Binary Search
Hide Similar Problems
  (H) Search in Rotated Sorted Array (H) Find Minimum in Rotated Sorted Array II


分析:

思路首先:遍历一遍,直接记录最小值,时间复杂度是O(N),空间浮渣度O(1)

class Solution {
public:
    int findMin(vector<int>& nums) {
        int minum=nums[0];
        for(int i=1;i<nums.size();i++)
        {
            if(nums[i]<minum)
                minum=nums[i];
        }
        return minum;
    }
};


第二种方法

还是直接遍历,
按照题目所说数组应该是先上升,在下降,如果在某个地方出现下降了,这个值就是最小值

class Solution {
public:
    int findMin(vector<int>& nums) {
        int minum=nums[0];
        for(int i=1;i<nums.size();i++)
        {
            if(nums[i-1]>nums[i])
               { 
                   minum=nums[i];
                   break;
               }
        }
        return minum;
    }
};



第三种方法
例子1:nums[mid] 可能大于也可能小于nums[low],若大于将high=mid,小于low=mid+1
4 5 6 7 0 1 2
例子2:nums[mid] 一直大于 nums[low],则需要将high=mid
0 1 2 4 5 6 7
例子3:nums[mid] 一直小于 nums[low],则需要将low=mid+1
7 6 5 4 2 1 0
low mid high
当nums[mid] == nums[low]时,说明已经找到

//思路首先:第三种方法,二分法
//
class Solution {
public:
    int findMin(vector<int>& nums) {
        if(nums.empty())
            return 0;
        if(nums.size() == 1)
            return nums[0];

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


注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/50424986

原作者博客:http://blog.csdn.net/ebowtang

你可能感兴趣的:(LeetCode,数据结构,算法,面试,ACM)