問題:函數
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.this
Example:spa
MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); --> Returns -3. minStack.pop(); minStack.top(); --> Returns 0. minStack.getMin(); --> Returns -2.
解決:對象
【注】要實現上面四個函數。element
① 大致上與傳統的stack相同,不一樣的是getMin方法,獲得全部棧中數據的最小值;使用兩個棧,一個保存正常數據,另外一個保存最小值。get
public class MinStack { // 117ms
private Stack<Integer> s1 = new Stack<>();//直接存儲
private Stack<Integer> s2 = new Stack<>();//存放每次比較時較小的數
/** initialize your data structure here. */
public MinStack() {}
public void push(int x) {
s1.push(x);
if(s2.isEmpty() || s2.peek() >= x) s2.push(x);
}
public void pop() { //第一次POP出的數值若爲最小值,則它之下的一個數仍是最小值,也須要POP
int x = s1.pop();
if(s2.peek() == x) s2.pop();
//不能使用s2.peek() == s1.peek()進行比較,由於peek方法返回對象的類型是Object,
//使用==比較無效,由於它們返回的是兩個不一樣的對象
}
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();
*/it
② 只使用棧保存數據,使用一個變量保存最小值。class
public class MinStack { // 147ms
private Stack<Integer> s = new Stack<>();
private int minVal = Integer.MAX_VALUE;
public MinStack(){}
public void push(int x){
if(x <= minVal){
s.push(minVal);
minVal = x;
}
s.push(x);
}
public void pop(){
if(s.pop() == minVal) minVal = s.pop();
}
public int top(){
return s.peek();
}
public int getMin(){
return minVal;
}
}變量
③ 本身編寫StackNode類,在本身編寫的stackNode中加入了最小值,能夠減小判斷。object
public class MinStack { //115ms StackNode head = null; /** initialize your data structure here. */ public MinStack() {} public void push(int x) { if (head==null){ head = new StackNode(x,x); }else{ StackNode newHead = new StackNode(x,Math.min(head.min,x)); newHead.next = head; head = newHead; } } public void pop() { head = head.next; } public int top() { return head.val; } public int getMin() { return head.min; } class StackNode{ int val; int min; StackNode next = null; public StackNode(int v,int min) { this.val = v; this.min = min; } } }