155. Min Stack。

来源:互联网 发布:wifi模块怎么传输数据 编辑:程序博客网 时间:2024/06/05 03:33

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.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); –> Returns -3.
minStack.pop();
minStack.top(); –> Returns 0.
minStack.getMin(); –> Returns -2.


刚开始的想法就比较简单,认为单纯的以一个标志位来记录最小的数值即可,但是仔细思考之后发现,如果标志位记录的是最小的数值,那么当这个数值被pop掉之后就无法找到下一个最小的数值了。所以比较经典做法就是维护两个stack,一个就是普通的栈,另一个是最小值的栈。首先当一个x进行入栈时,直接进入普通的栈,然后将此时的x与最小值栈的栈顶元素进行比较,如果x比栈顶元素大,那么不需要做处理。如果x比较小的话就需要将x入栈到最小值的栈。如果调用getMin的话直接将最小值栈栈顶出栈即可。如果进行pop操作的话,先直接将普通栈进行出栈,然后判断此时出栈的元素和最小值栈栈顶元素是否一致,如果一致的话就说明此时出栈的元素是最小的,那么需要将最小值栈也出栈了。

code:

#include <iostream>#include <stack>using namespace std;class MinStack {public:    stack<int> dataStack;    stack<int> minStack;    /** initialize your data structure here. */    void push(int x) {        dataStack.push(x);        if (minStack.empty()) {            minStack.push(x);            return;        }        int minnum = minStack.top();        if (minnum >= x) {//注意这里需要等于            minStack.push(x);        }    }    void pop() {        int num = dataStack.top();        int minnum = minStack.top();        if (num == minnum) {            dataStack.pop();            minStack.pop();            return;        }        dataStack.pop();    }    int top() {        return dataStack.top();    }    int getMin() {        return minStack.top();    }};int main() {    MinStack obj;    obj.push(1);    obj.push(3);    obj.push(5);    cout << obj.getMin();    obj.pop();    cout << obj.getMin();}
原创粉丝点击