码迷,mamicode.com
首页 > 其他好文 > 详细

<LeetCode OJ> Find Minimum in Rotated Sorted Array【153】

时间:2015-12-29 13:02:06      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

153. Find Minimum in Rotated Sorted Array

My Submissions
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


















//思路首先:遍历一遍时间复杂度是O(N)
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;
    }
};


//思路首先:第三种方法,二分法
//
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];
    }
};



<LeetCode OJ> Find Minimum in Rotated Sorted Array【153】

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!