33、簡單的棧實現
阿新 • • 發佈:2018-11-16
一開始想的是直接使用一個棧來儲存所有的資料,但是會發現在尋找最小值時會有時間的不夠
因此考慮使用兩個棧來儲存,一個就是棧,另一個就是儲存最小值
class MinStack { /** initialize your data structure here. */ Stack<Integer> s1; Stack<Integer> s2; public MinStack() { s1 = new Stack<>(); s2 = new Stack<>(); } public void push(int x) { if(s2.isEmpty()){ s2.push(x); } else if(x <= s2.peek()){ s2.push(x); } s1.push(x); } public void pop() { if(s1.peek().equals(s2.peek())){ **//這裡一定要是比較的是值,因此使用的是equals,一定要注意** s2.pop(); } s1.pop(); } public int top() { return s1.peek(); } public int getMin() { return s2.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(); */
需要注意的是比較的時候是進行值的比較而不是地址的比較,== 相當於比較地址
排名高的程式碼,思路都差不多,其實都是在取出最小值的時候進行優化,使用兩個棧進行
class MinStack { private LinkedList<Integer> stack; private LinkedList<Integer> minStack; /** initialize your data structure here. */ public MinStack() { stack = new LinkedList<>(); minStack = new LinkedList<>(); } public void push(int x) { stack.push(x); if(minStack.isEmpty() || x <= minStack.peek().intValue()) { minStack.push(x); } } public void pop() { if(stack.isEmpty() || minStack.isEmpty())return; if(stack.peek().intValue() == minStack.peek().intValue())minStack.pop(); stack.pop(); } public int top() { return stack.peek(); } public int getMin() { return minStack.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(); */