LeetCode-探索-初级算法-设计问题-2. 最小栈(个人做题记录,不是习题讲解)
LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/
- 最小栈
-
语言:java
-
思路:本来打算用1个ArrayList再存储排序后的堆栈之类的来实现快速获取最小值,但是后面想想好像很麻烦。看到网上有不错的文章,里面解法1感觉思路上比较好理解
https://www.cnblogs.com/lightwindy/p/8512214.html
-
代码(66ms):利用另外一个栈来存储最小值,存储条件即小于或等于当前值。一开始push的函数的if条件后半部分写成mins.peek()>x,导致如果出现入栈[0], [1], [0]后出栈[0]会使得mins为空,所以改成了>=.
class MinStack { Stack<Integer> vals; Stack<Integer> mins; /** initialize your data structure here. */ public MinStack() { vals = new Stack(); mins = new Stack(); } public void push(int x) { vals.push(x); if(mins.empty() || mins.peek() >= x) mins.push(x); } public void pop() { int min_peek = mins.peek(); int vals_peek = vals.peek(); if(vals_peek == min_peek) mins.pop(); vals.pop(); } public int top() { return vals.peek(); } public int getMin() { return mins.peek(); } } /** * 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(); */
-
参考代码(45ms):用数组代替stack,并且有在容量不足时扩容;其用另一个数组min来保存最小值,每个下标即在当前状态下(栈顶为top时)的栈中最小值(算是动态规划的方式吧,每个下标都存储从开头至今为止的当前状态最小值);
class MinStack { /** initialize your data structure here. */ private int[] s; private int[] min; private int top; public MinStack() { s = new int[10]; min = new int[10]; top = -1; } public void push(int x) { if (top == s.length - 1) { int[] temps = new int [s.length*2]; int[] tempm = new int [s.length*2]; for (int i = 0; i < s.length; i++){ temps[i] = s[i]; tempm[i] = min[i]; } s = temps; min = tempm; } s[top+1] = x; if (top < 0) { min[top+1] = x; } else { min[top+1] = x < min[top] ? x : min[top]; } top ++; } public void pop() { if (top >= 0){ top--; } } public int top() { if (top >= 0){ return s[top]; } else { return -1; } } public int getMin() { return min[top]; } } /** * 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(); */