在牛客网刷的,还是跟leetcode一样非acm模式,由于急着暑期实习题量不固定,八股算法轮刷
打卡内容偏个人笔记,本人水平一般(代码随想录稀里糊涂刷了一遍),从小白开始分析(甚至会分析语法),尽量一题多解深入探究(一般ac后看看前三个题解发散下思维),希望能对你有帮助
JZ9 用两个栈实现队列
描述
用两个栈来实现一个队列,使用n个元素来完成 n 次在队列尾部插入整数(push)和n次在队列头部删除整数(pop)的功能。 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
数据范围: n≤1000
要求:存储n个元素的空间复杂度为 O(n),插入与删除的时间复杂度都是 O(1)
分析
刷过的,记得是用一个负责入队,一个负责出队,但是写反了,模拟下发现stack1在倒入stack2后再push进一个会让一个元素残留
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while(!stack1.empty()) {
int tmp = stack1.pop();
stack2.push(tmp);
}
stack1.push(node);
}
public int pop() {
return stack2.pop();
}
}
实际上用两个栈模拟是利用逆序两次得到正序,而只需要保证在输出(pop)的时候正序就好了,就把倒入的代码都放到pop里了
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if (stack2.empty()){
while(!stack1.empty()) {
int tmp = stack1.pop();
stack2.push(tmp);
}
}
return stack2.pop();
}
}