剑指 Offer 30. 包含min函数的栈
剑指 Offer 30. 包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
各函数的调用总次数不超过 20000 次
点击查看代码
package 剑指offer二刷;
import java.util.Stack;
/**
* @author :szq
* @date :Created in 2022/3/18 10:15
* @description:剑指 Offer 30. 包含min函数的栈
* @modified By:
* @version: $
*/
class 包含min函数的栈 {
class MinStack {
/**
* initialize your data structure here.
*/
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
public MinStack() {
}
public void push(int x) {
s1.push(x);
if (!s2.empty()) { //如果第二个辅助栈不为空,则比较辅助栈的栈顶元素和刚准备进入元素的大小。
// if (s2.peek() < x)
// s2.push(s2.peek());
// else
// s2.push(x); //那个小入哪个
//三元表达式
s2.push(s2.peek()>x?x:s2.peek());
} else
s2.push(x);
}
public void pop() {
s1.pop();
s2.pop();
}
public int top() {
return s1.peek();
}
public int min() {
return s2.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.min();
*/
/**
* 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.min();
*/