out 栈相当于一个缓冲区域,把一部分入队的放到这个缓冲区域
当你拿出头元素的时候就可以直接去缓冲区去拿了,效率高,
LeetCode官网还给出了第二种解法,用到了均摊复杂度的知识,展示还没搞懂,这里介绍是方法一
class MyQueue {
Stack<Integer> input;
Stack<Integer> output;
/** Initialize your data structure here. */
public MyQueue() {
input = new Stack();
output = new Stack();
}
/** Push element x to the back of queue. */
public void push(int x) {
input.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(!output.isEmpty()) {
return output.pop();
}else {
while(!input.isEmpty()) {
output.push(input.pop());
}
return output.pop();
}
}
/** Get the front element. */
public int peek() {
if(!output.isEmpty()) {
return output.peek();
}else {
while(!input.isEmpty()) {
output.push(input.pop());
}
return output.peek();
}
}
/** Returns whether the queue is empty. */
public boolean empty() {
return output.isEmpty()&&input.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
下面是双队列实现
队列实现栈
我对这道题的理解是,准备两个队列,我分别命名为 input,队列和output 队列
output队列的第一位始终是最后一个进队列的,因此,每一次弹栈,都是弹出最后那个进队列的,这样就可以模拟栈的特性了 具体代码如下 `
class MyStack {
Queue<Integer> input;
Queue<Integer> output;
/** Initialize your data structure here. */
public MyStack() {
input = new LinkedList();
output = new LinkedList();
}
/** Push element x onto stack. */
public void push(int x) {
if(output.size()==0) {
output.offer(x);
}else {
while(output.size()!=0) {
input.offer(output.poll());//清空 output 队列
}
output.offer(x); //进队的放在output队列的第一位
while(input.size()!=0) {
output.offer(input.poll());//重改output 队列
}
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
if(output.peek()==null) {
return 0;
}
return output.poll();
}
/** Get the top element. */
public int top() {
if(output.peek()==null) {
return 0;
}
return output.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return output.peek()==null;
}
}
作者:deep-dark
链接:https://leetcode-cn.com/problems/two-sum/solution/shuang-dui-lie-shi-xian-zhan-by-deep-dark/