题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
ac:100%
思路:在push和pop的时候分别重新计算最小值,存入min中,这个时候min方法时间复杂度就是O(1)了
import java.util.Stack;
public class Solution {
private Stack<Integer> stack = new Stack<Integer>();
private int min;
private int size = 0;
public void push(int node) {
if(size == 0) {
min = node;
} else {
min = node < min ? node : min;
}
stack.push(node);
size++;
}
public void pop() {
if(!stack.empty()) {
if(stack.pop() == min) {
min = 999999999;
Stack<Integer> stackTemp = new Stack<Integer>();
Integer temp;
while((temp = stack.pop()) != null) {
min = min < temp ? min : temp;
stackTemp.push(temp);
if(stack.empty()) {
break;
}
}
while((temp = stackTemp.pop()) != null) {
stack.push(temp);
if(stackTemp.empty()) {
break;
}
}
}
size--;
}
if(size == 0) {
min = 0;
}
}
public int top() {
int temp = stack.pop();
stack.push(temp);
return temp;
}
public int min() {
return min;
}
}
来源:https://blog.csdn.net/qq_40638598/article/details/100043256