题目:
思路:
①设计两个栈,一个用来装元素,一个用来弹元素
②每当弹元素的栈为空时,将装元素的栈中的元素弹出并压入弹元素的栈
代码:
class MyQueue {
Stack<Integer> in_stack;
Stack<Integer> out_stack;
/** Initialize your data structure here. */
public MyQueue() {
in_stack = new Stack<Integer>();
out_stack = new Stack<Integer>();
}
/** Push element x to the back of queue. */
public void push(int x) {
in_stack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
if(out_stack.empty()){
while(!in_stack.empty()){
out_stack.push(in_stack.pop());
}
}
return out_stack.pop();
}
/** Get the front element. */
public int peek() {
if(out_stack.empty()){
while(!in_stack.empty()){
out_stack.push(in_stack.pop());
}
}
return out_stack.peek();
}
/** Returns whether the queue is empty. */
public boolean empty() {
if(in_stack.empty() && out_stack.empty())
return true;
return false;
}
}
/**
* 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();
*/
复杂度分析:
时间复杂度:
①push()
时间复杂度:O(1)
空间复杂度:O(n)
②pop()
时间复杂度:O(1)~O(n);摊还复杂度为O(1)
空间复杂度:O(1)
③empty()
时间复杂度:O(1)
空间复杂度:O(1)
④peak()
时间复杂度:O(1)
空间复杂度:O(1)
知识提要:摊还分析
摊还分析给出了所有操作的平均性能。
摊还分析的核心在于,最坏情况下的操作一旦发生了一次,那么在未来很长一段时间都不会再次发生,这样就会均摊每次操作的代价。