题目描述
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
题解
import java.util.Stack;
public class Solution {
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
public void push(int node) {
s1.push(node);
if(s2.isEmpty() || s2.peek() >= node) {
s2.push(node);
} else {
s2.push(s2.peek());
}
}
public void pop() {
s1.pop();
s2.pop();
}
public int top() {
return s1.peek();
}
public int min() {
return s2.peek();
}
}
本文介绍了一种特殊栈的数据结构实现,该栈包含一个能在O(1)时间复杂度内返回栈中最小元素的min函数。通过使用两个栈s1和s2,s1用于常规的元素压入和弹出操作,而s2则用于跟踪并保存最小值,确保min函数的高效调用。
308

被折叠的 条评论
为什么被折叠?



