LeetCode 题解工作台

设计循环双端队列

设计实现双端队列。 实现 MyCircularDeque 类: MyCircularDeque(int k) :构造函数,双端队列最大为 k 。 boolean insertFront() :将一个元素添加到双端队列头部。 如果操作成功返回 true ,否则返回 false 。 boolean in…

category

4

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 链表指针操作

bolt

答案摘要

我们可以使用一个数组来实现循环双端队列。我们维护一个指向队头的指针 和一个表示队列中元素个数的变量 ,以及一个表示队列容量的变量 。我们使用一个数组 来存储队列中的元素。 调用 时,首先检查队列是否已满,如果已满则返回 。如果队列不为空,则将 向前移动一个位置(使用模运算实现循环),然后将新元素插入到 位置,并将 加 1。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 链表指针操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

设计实现双端队列。

实现 MyCircularDeque 类:

  • MyCircularDeque(int k) :构造函数,双端队列最大为 k
  • boolean insertFront():将一个元素添加到双端队列头部。 如果操作成功返回 true ,否则返回 false
  • boolean insertLast() :将一个元素添加到双端队列尾部。如果操作成功返回 true ,否则返回 false
  • boolean deleteFront() :从双端队列头部删除一个元素。 如果操作成功返回 true ,否则返回 false
  • boolean deleteLast() :从双端队列尾部删除一个元素。如果操作成功返回 true ,否则返回 false
  • int getFront() ):从双端队列头部获得一个元素。如果双端队列为空,返回 -1 。
  • int getRear() :获得双端队列的最后一个元素。 如果双端队列为空,返回 -1
  • boolean isEmpty() :若双端队列为空,则返回 true ,否则返回 false  。
  • boolean isFull() :若双端队列满了,则返回 true ,否则返回 false

 

示例 1:

输入
["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"]
[[3], [1], [2], [3], [4], [], [], [], [4], []]
输出
[null, true, true, true, false, 2, true, true, true, 4]

解释
MyCircularDeque circularDeque = new MycircularDeque(3); // 设置容量大小为3
circularDeque.insertLast(1);			        // 返回 true
circularDeque.insertLast(2);			        // 返回 true
circularDeque.insertFront(3);			        // 返回 true
circularDeque.insertFront(4);			        // 已经满了,返回 false
circularDeque.getRear();  				// 返回 2
circularDeque.isFull();				        // 返回 true
circularDeque.deleteLast();			        // 返回 true
circularDeque.insertFront(4);			        // 返回 true
circularDeque.getFront();				// 返回 4
 

 

提示:

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • insertFrontinsertLastdeleteFrontdeleteLastgetFrontgetRearisEmptyisFull  调用次数不大于 2000 次
lightbulb

解题思路

方法一:数组

我们可以使用一个数组来实现循环双端队列。我们维护一个指向队头的指针 front\textit{front} 和一个表示队列中元素个数的变量 size\textit{size},以及一个表示队列容量的变量 capacity\textit{capacity}。我们使用一个数组 q\textit{q} 来存储队列中的元素。

调用 insertFront\textit{insertFront} 时,首先检查队列是否已满,如果已满则返回 false\text{false}。如果队列不为空,则将 front\textit{front} 向前移动一个位置(使用模运算实现循环),然后将新元素插入到 front\textit{front} 位置,并将 size\textit{size} 加 1。

调用 insertLast\textit{insertLast} 时,首先检查队列是否已满,如果已满则返回 false\text{false}。如果队列不为空,则计算新元素应该插入的位置(使用 front\textit{front}size\textit{size} 计算),将新元素插入到该位置,并将 size\textit{size} 加 1。

调用 deleteFront\textit{deleteFront} 时,首先检查队列是否为空,如果为空则返回 false\text{false}。如果队列不为空,则将 front\textit{front} 向后移动一个位置(使用模运算实现循环),并将 size\textit{size} 减 1。

调用 deleteLast\textit{deleteLast} 时,首先检查队列是否为空,如果为空则返回 false\text{false}。如果队列不为空,则将 size\textit{size} 减 1。

调用 getFront\textit{getFront} 时,首先检查队列是否为空,如果为空则返回 1-1。如果队列不为空,则返回 q[front]\textit{q}[\textit{front}]

调用 getRear\textit{getRear} 时,首先检查队列是否为空,如果为空则返回 1-1。如果队列不为空,则计算队尾元素的位置(使用 front\textit{front}size\textit{size} 计算),并返回该位置的元素。

调用 isEmpty\textit{isEmpty} 时,检查 size\textit{size} 是否为 00

调用 isFull\textit{isFull} 时,检查 size\textit{size} 是否等于 capacity\textit{capacity}

以上操作的时间复杂度均为 O(1)O(1),空间复杂度为 O(k)O(k),其中 kk 是队列的容量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
class MyCircularDeque:
    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the deque to be k.
        """
        self.q = [0] * k
        self.front = 0
        self.size = 0
        self.capacity = k

    def insertFront(self, value: int) -> bool:
        """
        Adds an item at the front of Deque. Return true if the operation is successful.
        """
        if self.isFull():
            return False
        if not self.isEmpty():
            self.front = (self.front - 1 + self.capacity) % self.capacity
        self.q[self.front] = value
        self.size += 1
        return True

    def insertLast(self, value: int) -> bool:
        """
        Adds an item at the rear of Deque. Return true if the operation is successful.
        """
        if self.isFull():
            return False
        idx = (self.front + self.size) % self.capacity
        self.q[idx] = value
        self.size += 1
        return True

    def deleteFront(self) -> bool:
        """
        Deletes an item from the front of Deque. Return true if the operation is successful.
        """
        if self.isEmpty():
            return False
        self.front = (self.front + 1) % self.capacity
        self.size -= 1
        return True

    def deleteLast(self) -> bool:
        """
        Deletes an item from the rear of Deque. Return true if the operation is successful.
        """
        if self.isEmpty():
            return False
        self.size -= 1
        return True

    def getFront(self) -> int:
        """
        Get the front item from the deque.
        """
        if self.isEmpty():
            return -1
        return self.q[self.front]

    def getRear(self) -> int:
        """
        Get the last item from the deque.
        """
        if self.isEmpty():
            return -1
        idx = (self.front + self.size - 1) % self.capacity
        return self.q[idx]

    def isEmpty(self) -> bool:
        """
        Checks whether the circular deque is empty or not.
        """
        return self.size == 0

    def isFull(self) -> bool:
        """
        Checks whether the circular deque is full or not.
        """
        return self.size == self.capacity


# Your MyCircularDeque object will be instantiated and called as such:
# obj = MyCircularDeque(k)
# param_1 = obj.insertFront(value)
# param_2 = obj.insertLast(value)
# param_3 = obj.deleteFront()
# param_4 = obj.deleteLast()
# param_5 = obj.getFront()
# param_6 = obj.getRear()
# param_7 = obj.isEmpty()
# param_8 = obj.isFull()
speed

复杂度分析

指标
时间O(1)
空间O(k)
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate should demonstrate knowledge of linked-list pointer manipulation, especially handling both ends of a deque.

  • question_mark

    Look for an understanding of circular structures and how they impact space and time complexity.

  • question_mark

    Candidates who can explain efficient handling of boundary conditions (overflow and underflow) will show solid problem-solving skills.

warning

常见陷阱

外企场景
  • error

    Forgetting to update both `next` and `prev` pointers correctly when inserting or deleting elements.

  • error

    Not handling the circular nature of the deque properly, especially with the front and rear pointers.

  • error

    Failing to efficiently manage the size of the deque, leading to overflow or underflow errors.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Implementing a deque using arrays or other data structures for comparison of space and time efficiency.

  • arrow_right_alt

    Designing a fixed-size deque with resizing capabilities when full or empty.

  • arrow_right_alt

    Optimizing memory usage by adjusting node structure or implementing a static array-based deque.

help

常见问题

外企场景

设计循环双端队列题解:链表指针操作 | LeetCode #641 中等