232. Implement Queue using Stacks
problem description
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
Notes:
You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
algorithm thought
使用stack实现一个queue,这里需要两个栈。第一次做的时候,我实现的pop操作,时间复杂度为O(n),并且认为应该没有地方能改了。但是这次抱着试一试的心态去看了discuss,发现确实有很厉害的算法,将所有操作的平均时间复杂度降低到了O(1)
使用一个input stack和output stack。如果需要peek或者pop,直接返回output stack的元素。如果output stack为空,就将input stack中所有元素push到output中。这里确实需要O(n)的时间,但是和平均O(1)不矛盾。
一般的做法是,一直弹出,直到最后一个数,返回,然后将栈复原。但是这里直接保存在output stack中。因为,只要反转一次,就不用再复原了,直接保持状态,之后就可以不用反转。
code
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
input.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int res=peek();
output.pop();
return res;
}
/** Get the front element. */
int peek() {
if(output.size()==0){
while(input.size()){
output.push(input.top()),input.pop();
}
}
return output.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return input.empty()&&output.empty();
}
private:
stack<int> input,output;
};
/**
* 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();
* bool param_4 = obj->empty();
*/
algorithm analysis
由于这个算法,对于每个数字只需要一次入栈操作,和一次转移栈操作以及一次出栈操作。这几个操作是O(n)的,所以对于每个数字而言,平均时间复杂度是O(1)
Last updated