Leetcode: 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.

这是一道关于栈的题目,整体来说比较简单。我最开始想的时候想的太简单,以为使用一个栈st, 再维护一个最小值变量就好了。突然发现pop()操作之后需要更新这个最小值,那就需要知道第二小的值,这个第二小的值怎么找呢?于是乎我想到了使用另外一个栈minst专门来存储最小值。push()操作的时候每当x小于或等于(注意不是小于,之所以小于等于是为了元素重复的情况)minst的栈顶元素,minst也push x入栈。pop()操作时,如果pop出来的元素等于minst栈顶元素,那么minst栈也出栈。

这道题思路很简单,到时语法卡了我一会儿,老是过不了,一段时间不练手生啊。我的语法问题又出在==跟equals()上面。我栈的定义是Stack<Integer>。Integer是一个object。那么判断两个栈栈顶元素相等就不能写成 st.peek() == minst.peek(),这是地址相等,equals才是值相等。要改的话要么就改用equals,要么定义一个int elem = st.pop(); 再判断if (elem == minst.peek()), 这里是一个int 变量跟Integer对象相比,而不是两个Integer对象相比,==在这里就是表示值相等。

 1 class MinStack {
 2     Stack<Integer> st;
 3     Stack<Integer> minst;
 4     
 5     public MinStack() {
 6         this.st = new Stack<Integer>();
 7         this.minst = new Stack<Integer>();
 8     }
 9     
10     public void push(int x) {
11         st.push(x);
12         if (minst.empty() || minst.peek()>=x) {
13             minst.push(x);
14         }
15     }
16 
17     public void pop() {
18         if (st.isEmpty()) {
19             return;
20         }
21         if (st.peek().equals(minst.peek())) {
22             minst.pop();
23         }
24         st.pop();
25     }
26 
27     public int top() {
28         if (!st.isEmpty()) {
29             return st.peek();
30         }
31         return Integer.MAX_VALUE;
32     }
33 
34     public int getMin() {
35         if (!minst.isEmpty()) {
36             return minst.peek();
37         }
38         return Integer.MAX_VALUE;
39     }
40 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值