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.
Have you met this question in a real interview?
思路 1 : 就是多设置一个 minStack来存储一下最小值, push 和 pop 时候判断一下。
思路2 : 这个具有更小的空间复杂度, 设置一个 min 作为标记, 在 stack 里面存储 和 min 的差值。
class MinStack {
Stack<Integer> s = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
s.push(x);
if(minStack.isEmpty() || x <= minStack.peek()){//-----
minStack.push(x);
}
}
public void pop() {
int num = s.pop();
if(num == minStack.peek()){
minStack.pop();
}
}
public int top() {
return s.peek();
}
public int getMin() {
return minStack.peek();
}
}
public class MinStack {
long min;
Stack<Long> stack;//有减法,所以用long,将数据越界考虑在内
public MinStack(){
stack=new Stack<>();
}
public void push(int x) {
if (stack.isEmpty()){
stack.push(0L);
min=x;
return;
}
stack.push(x-min);//Could be negative if min value needs to change
if (x<min) min=x;
}
public void pop() {
if (stack.isEmpty()) return;
long pop=stack.pop();
if (pop<0) min=min-pop;//If negative, increase the min value
}
public int top() {
long top=stack.peek();
if (top>0){
return (int)(top+min);
}else{
return (int)(min);
}
}
public int getMin() {
return (int)min;
}
}