问题描述:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
压栈,移除栈顶,查看栈顶,查找最小 均为O(1)
Implement the MinStack class:
MinStack() initializes the stack object.
void push(val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
思路一:
一开始我想用两个stack,但是没有想出来。后来看了参考答案,方法是这个样子的,其实我的思路比较接近了。两个栈A和B,如果当前进栈元素小于等于B中栈顶的元素,则A,B均添加这个元素,否则只在A中添加。top()就返回A的栈顶,getMin()就返回B的栈顶。pop()要当心,如果A的栈顶与B的栈顶不同,则直接删除A的栈顶;若相同。则两个栈的栈顶都要被删除。
这个方法的实现不难,若今后有时间再说
我这次尝试用另外一种方法实现,就是栈中的元素不是单纯一个数,而是一个数对,key为这个数的值,value为以这个数为栈顶栈中的最小值。
代码如下:
```java
class MinStack {
private List<Pair<Integer,Integer>> myList;
private int top;
/** initialize your data structure here. */
public MinStack() {
myList = new ArrayList<Pair<Integer,Integer>>();
top = -1;
}
public void push(int val) {
top++;
if (myList.size()==0){
myList.add(new Pair(val, val));
}
else{
myList.add(new Pair(val, Math.min(val, myList.get(top-1).getValue())));
}
}
public void pop() {
myList.remove(top);
top--;
}
public int top() {
return myList.get(top).getKey();
}
public int getMin() {
return myList.get(top).getValue();
}
}