Fork me on GitHub

【LeetCode】155. Min Stack

题目:

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

提示:

这道题可以通过使用两个stack实现对最小值的记录,每次push进来一个数后,比较该数是否小于当前最小值,如果小于的话就push进保存最小值的stack当中,由于stack“先进后出”的特性,因此后面Push进来的较大的值并不会影响最小值的判断,因为这个较大的值会在之前push进来的较小的值之前pop出去。

另外还可以只使用一个stack,具体的方法就是在stack中存放pair,每个pair的first存放的是值,second存放的是若当前pair在顶部状态时的最小值。

代码:

2stack:

class MinStack {
    stack<int> s;
    stack<int> min;
public:
    void push(int x) {
        if (min.empty() || x <= getMin()) min.push(x);
        s.push(x);
    }

    void pop() {
        if (s.top() == min.top()) min.pop();
        s.pop();
    }

    int top() {
        return s.top();
    }

    int getMin() {
        return min.top();
    }
};

 1stack:

class MinStack {
    typedef pair<int,int> pairt;
    deque<pairt> stack;
public:
    void push(int x) {
        if (stack.size())
            stack.push_back(make_pair(x, min(x,getMin())));
        else 
            stack.push_back(make_pair(x, x));
    }

    void pop() {
        stack.pop_back();
    }

    int top() {
        return stack.back().first;
    }

    int getMin() {
        return stack.back().second;
    }
};
posted @ 2015-09-09 13:50  __Neo  阅读(303)  评论(0编辑  收藏  举报