题目描述:
实现一个特殊的栈,在实现栈的基本功能的基础上再实现返回栈中最小元素的功能
要求:
1. pop, push,getMin 操作的时间复杂度都是O(1)
2. 设计的栈类型可以使用现成的栈结构
我的代码:
import java.util.Stack;
/**
* 含有getMin功能的栈,典型的以空间换时间
* @author root
*/
public class Solution {
//存放数据
Stack<Integer> stackData = new Stack<Integer>();
//栈顶元素为当前栈中的最小值
Stack<Integer> stackMin = new Stack<Integer>();
public void push(int node) {
stackData.push(node);
if(stackMin.isEmpty()){
stackMin.push(node);
}else if(node<=stackMin.peek()){
//同步更新最小值
stackMin.push(node);
}
}
public void pop() {
int value = stackData.pop();
if(value == stackMin.peek()){
//同步更新最小值
stackMin.pop();
}
}
public int top() {
return stackData.peek();
}
public int min() {
return stackMin.peek();
}
}