Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
一、题目描述:
题目来源:LeetCode>包含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 次
二、思路分析:
- 当1栈顶作为最小值pop后,全栈最小值也会pop。
- 最小值也构成一个栈2,当1栈顶作为最小值push时,最小值栈2也push
- 在1栈顶作为最小值pop时,最小值栈2也pop。
- 使用两个栈,一个作为最小值栈或使用一个栈,每次进出都把最小值和栈顶元素都带上,一次使用两个栈帧
三、AC 代码:
class MinStack {
private LinkedList<Integer> stack;
private LinkedList<Integer> minStack;
public MinStack() {
this.stack = new LinkedList<Integer>();
this.minStack = new LinkedList<Integer>();
}
public void push(int x) {
stack.push(x);
if (minStack.isEmpty() || minStack.peekFirst() >= x) minStack.push(x);
}
public void pop() {
int top = stack.pop();
if (minStack.isEmpty()) {
return;
}
if (minStack.peekFirst() == top) {
minStack.pop();
}
}
public int top() {
return stack.isEmpty() ? -1 : stack.peekFirst();
}
public int min() {
return minStack.isEmpty() ? -1 : minStack.peekFirst();
}
}
也可用双端队列实现
class Solution {
public void example() {
Deque<Integer> stack = new LinkedList<Integer>();
stack.offer(0);
int num = stack.pollLast();
int num = stack.peekLast();
Deque<Integer> queue = new LinkedList<Integer>();
queue.offer(0);
int num = queue.poll();
int num = queue.peekFisrt();
}
}
四、总结:
- 此题要求的栈,与普通栈不同,多了一个获取最小值的方法。
- 栈比较简单,主要还是看怎么以 O(1) 的时间复杂度查找栈中的最小值。