LeetCode155:Min Stack

来源:互联网 发布:光猫超级密码开启端口 编辑:程序博客网 时间:2024/05/01 12:59


LeetCode155:Min Stack

一、题目地址:https://leetcode.com/problems/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.

 Tags:Stack & Data Structure

三、代码:

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

0 0
原创粉丝点击