
方法1: pair。其实这道题最重要的就是要track 最小值并保存下来,所以一定需要额外空间。时间复杂1,空间复杂n。详细解释直接看lc官方解答。
class MinStack {
Stack<int[]> stack = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(stack.isEmpty()) stack.push(new int[]{x, x});
else {
int[] curr = new int[]{x, Math.min(x, stack.peek()[1])};
stack.push(curr);
}
}
public void pop() {
stack.pop();
}
public int top() {
return stack.peek()[0];
}
public int getMin() {
return stack.peek()[1];
}
}
/**
* 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();
*/
方法2: two stack。方法1的优化。时间复杂1,空间复杂n。
class MinStack {
Stack<Integer> s = new Stack<>();
Stack<Integer> mStack = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
if(s.isEmpty() && mStack.isEmpty()){
s.push(x);
mStack.push(x);
}else{
if(x <= mStack.peek()){
s.push(x);
mStack.push(x);
}else{
s.push(x);
}
}
}
public void pop() {
int curr = s.pop();
if(curr == mStack.peek()) mStack.pop();
}
public int top() {
return s.peek();
}
public int getMin() {
return mStack.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();
*/
方法3: two stacks + pair,方法3的优化。时间复杂1,空间复杂n。
class MinStack {
Stack<Integer> s = new Stack<>();
Stack<int[]> mStack = new Stack<>();
/** initialize your data structure here. */
public MinStack() {
}
public void push(int x) {
s.push(x);
if(mStack.isEmpty() || x < mStack.peek()[0]){
mStack.push(new int[]{x,1});
}else if(x == mStack.peek()[0]){
mStack.peek()[1]++;
}
}
public void pop() {
int curr = s.pop();
if(curr == mStack.peek()[0]) mStack.peek()[1]--;
if(mStack.peek()[1] == 0) mStack.pop();
}
public int top() {
return s.peek();
}
public int getMin() {
return mStack.peek()[0];
}
}
/**
* 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();
*/
本文介绍三种实现最小栈的方法:使用元素对、双栈以及双栈加元素对的方式。每种方法都详细展示了如何在O(1)时间内进行push、pop、top和获取最小值的操作。
774





