问题:函数
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; } } }