[Jianzhi Offer] 9. Use two stacks to implement the queue. Difficulty Level: Easy. Problem-solving ideas are worth learning

1. Topic

Implement a queue with two stacks. The declaration of the queue is as follows. Please implement its two functions appendTail and deleteHead to complete the function of inserting an integer at the tail of the queue and deleting an integer at the head of the queue respectively. (If there is no element in the queue, the deleteHead operation returns -1)

Example 1:

输入:
["CQueue","appendTail","deleteHead","deleteHead","deleteHead"]
[[],[3],[],[],[]]
输出:[null,null,3,-1,-1]

Example 2:

输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]

2. My solution: slow

Idea: Use a reverse auxiliary stack, each time the head element of the queue is deleted, the stack is popped out of the stack in turn, and the bottom element of the stack is deleted before being pushed into the stack.

Every time the head element is deleted, a complete pop-up and stack-pull operation is required, and there are repeated operations, resulting in high time complexity.

code:

class CQueue:
    def __init__(self):
        self.stack=[]
        self.inv_stack=[]   # stack的逆序

    def appendTail(self, value: int) -> None:
        self.stack.append(value)

    def deleteHead(self) -> int:
        if not self.stack:
            return -1
        # stack 逐元素出栈
        while self.stack:
            self.inv_stack.append(self.stack.pop())

        # 在stack 逐元素入栈之前保留队列头部元素
        head=self.inv_stack.pop()

        # stack 逐元素入栈
        while self.inv_stack:
            self.stack.append(self.inv_stack.pop())
        return head
       

# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()

Results of the:

执行用时:1084 ms, 在所有 Python3 提交中击败了 12.81% 的用户
内存消耗:20.2 MB, 在所有 Python3 提交中击败了 17.19% 的用户

3. Advanced solution: fast

code:

class CQueue:
    def __init__(self):
        self.stack = []
        self.inv_stack = []

    def appendTail(self, value: int) -> None:
        self.stack.append(value)

    def deleteHead(self) -> int:
        # 每次删除队列头部元素就从 inv_stack 中删除尾部元素,直到 inv_stack 为空
        if self.inv_stack: 
            return self.inv_stack.pop()
        if not self.stack: 
            return -1
        
        # inv_stack 为空时,将 stack 逆序输入到 inv_stack 中
        while self.stack:
            self.inv_stack.append(self.stack.pop())
        return self.inv_stack.pop()

Results of the:

执行用时:312 ms, 在所有 Python3 提交中击败了 70.07% 的用户
内存消耗:20.1 MB, 在所有 Python3 提交中击败了 22.39% 的用户

Compared with my solution, this solution only executes the pop-up operation of the stack, but not the push-in operation of the stack. Instead, return the self.inv_stack.pop() method first to ensure that the head element of the queue can be returned every time.

The premise that this solution can be executed efficiently is that the title does not require the function of printing all the elements of the queue at any time; and when self.inv_stack is not empty, self.stack is an empty stack, and the queue elements cannot be printed at this time.

If the title requires a function that can print all the elements of the queue at any time, I can only use my solution.

Guess you like

Origin blog.csdn.net/qq_43799400/article/details/131158486