LeetCode

[LeetCode] Easy - 232 Implement Queue using Stacks

NIMHO 2022. 12. 16. 11:32
728x90

▶232 - Implement Queue using Stacks

문제

mplement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).

Implement the MyQueue class:

  • void push(int x) Pushes element x to the back of the queue.
  • int pop() Removes the element from the front of the queue and returns it.
  • int peek() Returns the element at the front of the queue.
  • boolean empty() Returns true if the queue is empty, false otherwise.

 

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, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.

 

예제

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

 

풀이

stack을 이용해서 queue를 구현해야 한다.list 특성을 이용해도 충분히 풀 수 있는 문제이다.하지만 stack은 list라서, popleft()를 할 수 없다.

 

def pop()를 할 때 [0]을 ans에 빼주고 queue = queue[1:]를 해주면 큐에 1번째부터 저장할 수 있다.그렇게 되면 자연스럽게 0번째가 빠지게 되고, FIFO를 구현할 수 있다.

class MyQueue:

    def __init__(self):
        self.queue = []
        return None

    def push(self, x: int) -> None:
        self.queue.append(x)
        return None

    def pop(self) -> int:
        ans = self.queue[0]
        self.queue = self.queue[1:]
        return ans

    def peek(self) -> int:
        return self.queue[0]

    def empty(self) -> bool:
        if len(self.queue) == 0:
            return True
        else:
            return False


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

runtime은 양호하지만, memory는 그렇게 좋지 못한 것 같다.

그 부분을 수정해서 다시 풀어봐야겠다.

728x90