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.
题解:
设计一个栈,能够实现出入栈,获得栈顶元素,而且能不断获得出入栈操作后栈内最小的元素。
解决思路:
1、由于要不断在出入栈操作后获得栈内最小的元素,所以并不能直接在类里用一个min变量来存储最小的元素,因为这样无法更新min的值。由此就设计了一个内部类,但这里有一个问题,如果我们单纯的设计一个普通的内部类,提交后会memory limited exceeded。单步调试会发现,每一个内部类对象都会包含一个this,然后这个this又包含了我们的栈,会浪费非常多的空间。这个时候我想起了用static修饰内部类,让其变成静态类,然后就OK了。
![](https://img-my.csdn.net/uploads/201411/18/1416278885_1796.png)
想要深入了解的话可以看看我转载的这个文章:http://blog.csdn.net/u012403246/article/details/41243319
2、设计两个栈,一个栈存储数据,第二个栈存储对应最小值。
3、或者不使用JAVA包里的Stack,自己通过设计类去得到一个栈,实现以上功能.
三、代码:
1、
class MinStack {
Stack<Elem> stack = new Stack<MinStack.Elem>();
public void push(int x) {
if(stack.isEmpty() || x < stack.peek().min){
stack.push(new Elem(x, x));
}else{
stack.push(new Elem(stack.peek().min, x));
}
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek().val;
}
public int getMin() {
return stack.peek().min;
}
public static class Elem{
int min;
int val;
public Elem(int min,int val) {
this.min = min;
this.val = val;
}
}
}
2、by:
zkfairytale
class MinStack {
// stack: store the stack numbers
private Stack<Integer> stack = new Stack<Integer>();
// minStack: store the current min values
private Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
// store current min value into minStack
if (minStack.isEmpty() || x <= minStack.peek())
minStack.push(x);
stack.push(x);
}
public void pop() {
// use equals to compare the value of two object, if equal, pop both of them
if (stack.peek().equals(minStack.peek()))
minStack.pop();
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
3、by:
class MinStack {
Node top = null;
public void push(int x) {
if (top == null) {
top = new Node(x);
top.min = x;
}
else {
Node temp = new Node(x);
temp.next = top;
top = temp;
top.min = Math.min(top.next.min, x);
}
return;
}
public void pop() {
top = top.next;
return;
}
public int top() {
return top == null ? 0 : top.val;
}
public int getMin() {
return top == null ? 0 : top.min;
}
}
class Node {
int val;
int min;
Node next;
public Node(int val) {
this.val = val;
}
}