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.
Example:
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.
這個我想了很久,其實挺簡單的,你可以發揮你的想象使用任何方法來實現這么一個Min Stack,而我的思想局限在了使用數組,棧這些常見的數據結構上。我們完全可以拋棄這些。
使用一個自定義類,這個類來代表棧里的每一個元素,這個類有三個屬性:val,min,down。
val代表當前元素的值
min代表當前棧里最小的值是多少
down代表誰在這個元素下面
每次壓棧時,我都可以把當前的元素的值和棧里最小的值做對比得到新的最小值。
public class MinStack {
private Item head = null;
public MinStack() {}
public void push(int x) {
if (head==null)
head = new Item(x,x,null);
else
head = new Item(x,x>head.min?head.min:x,head);
}
public void pop() {
head = head.down;
}
public int top() {
return head.val;
}
public int getMin() {
return head.min;
}
private class Item {
public int val;
public int min;
public Item down;
public Item(int val,int min,Item down) {
this.val = val;
this.min = min;
this.down = down;
}
}
}