Leetcode Min Stack

来源:互联网 发布:淘宝c店保证金是多少 编辑:程序博客网 时间:2024/06/12 18:12

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.

    设计一个栈,使得它有如下功能:出栈,入栈,获得栈顶元素,获得最小元素,时间复杂度是O(1),利用两个栈,一个负责存储元素,一个负责存储最小元素。

  • class MinStack {public:    stack<int> stack1;    stack<int> stack2;    void push(int x) {        stack1.push(x);        if(stack2.empty())        {            stack2.push(x);        }        else        {            if(x<=stack2.top())            {                stack2.push(x);            }        }    }    void pop() {        if(stack1.top() == stack2.top())        {            stack2.pop();        }        stack1.pop();    }    int top() {        return stack1.top();    }    int getMin() {        return stack2.top();    }};


0 0
原创粉丝点击