标签:元素 oid pre cal param lse ali ems code
push(x) -- 将元素 x 推入栈中。
pop() -- 删除栈顶的元素。
top() -- 获取栈顶元素。
getMin() -- 检索栈中的最小元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/min-stack
用栈来实现一个优先队列,通过增加一个辅助栈来存放最小元素,数据栈pop时同步pop,入栈时与辅助栈栈顶比较,较小的加入辅助栈;
代码如下:
class MinStack { private Stack<Integer>data; private Stack<Integer>help; /** initialize your data structure here. */ public MinStack() { data=new Stack<>(); help=new Stack<>(); } public void push(int x) { data.add(x); if(help.isEmpty()||help.peek()>=x) help.add(x); else help.add(help.peek()); } public void pop() { if(!data.isEmpty()){ data.pop(); help.pop(); } } public int top() { if(!data.isEmpty()) return data.peek(); else return -1; } public int getMin() { if(!help.isEmpty()){ return help.peek(); } else return -1; } } /** * Your MinStack object will be instantiated and called as such: * MinStack obj = new MinStack(); * obj.push(x); * obj.pop(); * int param_3 = obj.top(); * int param_4 = obj.getMin(); */
标签:元素 oid pre cal param lse ali ems code
原文地址:https://www.cnblogs.com/teensSpirit-code-life/p/11773383.html