代码改变世界

[LeetCode] 232. Implement Queue using Stacks_Easy tag: stack

2019-05-13 05:37  Johnson_强生仔仔  阅读(272)  评论(0编辑  收藏  举报

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 toppeek/pop from topsize, 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).

 

这个题目就是利用两个stack,一个来存放顺序的stack,另外一个存放逆序的stack(也就是正序的queue),如果queue为空的时候要pop(),那么就将stack中的全部移到queue中。

Note:时间复杂度在这里不是看的最坏时间复杂度,而是average 时间复杂度,虽然一次pop的最坏情况可能是 O(n), 但是平均的时间是O(1). 

tips:看每一步时间复杂度时不太明确的时候,可以看每一个data,比如这个两个stack中的每个num,最多会进出stack一次,进出queue一次,共4次,是O(1) 的时间复杂度, 所以每次操作就是O(1) 的时间复杂度。

Code

class MyQueue:
    def __init__(self):
        self.stack = []
        self.queue = []
    def push(self, x) -> None:
        self.stack.append(x)
    def pop(self) -> int:
        if not self.queue:
            while self.stack:
                self.queue.append(self.stack.pop())
        if self.queue:
            return self.queue.pop()
    def peek(self) -> int:
        return self.queue[-1] if self.queue else self.stack[0]
    def empty(self) -> bool:
        return not self.queue and not self.stack