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

[LintCode] Min Stack 最小栈

时间:2016-11-14 07:50:37      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:博客   notice   max   eve   operation   http   .com   opera   strong   

 

Implement a stack with min() function, which will return the smallest number in the stack.

It should support push, pop and min operation all in O(1) cost.

 Notice

min operation will never be called if there is no number in the stack.

Example
push(1)
pop()   // return 1
push(2)
push(3)
min()   // return 2
push(1)
min()   // return 1

 

LeetCode上的原题,请参见我之前的博客Min Stack.

 

解法一:

class MinStack {
public:
    MinStack() {}

    void push(int number) {
        m1.push(number);
        if (m2.empty() || m2.top() >= number) {
            m2.push(number);
        }
    }

    int pop() {
        if (m1.empty()) return -1;
        int t = m1.top(); m1.pop();
        if (!m2.empty() && m2.top() == t) m2.pop();
        return t;
    }

    int min() {
        if (!m2.empty()) return m2.top();
        return -1;
    }
private:
    stack<int> m1, m2;
};

 

解法二:

class MinStack {
public:
    MinStack():mn(INT_MAX) {}

    void push(int number) {
        if (number <= mn) {
            s.push(mn);
            mn = number;
        }
        s.push(number);
    }

    int pop() {
        int t = s.top(); s.pop();
        if (t == mn) {
            mn = s.top(); s.pop();
        }
        return t;
    }

    int min() {
        return mn;
    }

private:
    int mn;
    stack<int> s;
};

 

[LintCode] Min Stack 最小栈

标签:博客   notice   max   eve   operation   http   .com   opera   strong   

原文地址:http://www.cnblogs.com/grandyang/p/6060577.html

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