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

【LeetCode】Find Minimum in Rotated Sorted Array (2 solutions)

时间:2014-11-07 16:34:34      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   使用   sp   

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.

 

解法一:暴力解法,直接使用algorithm库中的求最小元素函数

需要遍历整个vector

class Solution {
public:
    int findMin(vector<int> &num) {
        if(num.empty())
            return 0;
        vector<int>::iterator iter = min_element(num.begin(), num.end());
        return *iter;
    }
};

bubuko.com,布布扣

 

解法二:利用sorted这个信息。如果平移过,则会出现一个gap,也就是从最大元素到最小元素的跳转。如果没有跳转,则说明没有平移。

比上个解法可以省掉不少时间,平均情况下不用遍历vector了。

class Solution {
public:
    int findMin(vector<int> &num) {
        if(num.empty())
            return 0;
        else if(num.size() == 1)
            return num[0];
        else
        {
            for(vector<int>::size_type st = 1; st < num.size(); st ++)
            {
                if(num[st-1] > num[st])
                    return num[st];
            }
            return num[0];
        }
    }
};

bubuko.com,布布扣

【LeetCode】Find Minimum in Rotated Sorted Array (2 solutions)

标签:style   blog   http   io   color   ar   os   使用   sp   

原文地址:http://www.cnblogs.com/ganganloveu/p/4081438.html

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