↓快轉到主要內容
  1. LeetCode/

LeetCode 622: Design Circular Queue

·1 分鐘· ·
LeetCode Medium Queue Design Array
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-09-14

  • 提交紀錄:Accepted(一次通過)

解題思路
#

環狀佇列用一個固定大小 k 的陣列,空間用完之後從頭開始重複使用。

只需要兩個變數:

  • head:第一個元素的位置。
  • count:目前有幾個元素。

其他位置都能算出來:

要找的位置公式
下一個要寫入的位置(head + count) % k
最後一個元素(head + count - 1) % k
出隊後的新 head(head + 1) % k

用 count 判斷空和滿,就不會遇到「head == tail 時到底是空還是滿」的問題。

我的解法
#

class MyCircularQueue:

    def __init__(self, k: int):
        self.buf = [0] * k
        self.head = 0
        self.count = 0

    def enQueue(self, value: int) -> bool:
        if self.isFull():
            return False
        self.buf[(self.head + self.count) % len(self.buf)] = value
        self.count += 1
        return True

    def deQueue(self) -> bool:
        if self.isEmpty():
            return False
        self.head = (self.head + 1) % len(self.buf)
        self.count -= 1
        return True

    def Front(self) -> int:
        return -1 if self.isEmpty() else self.buf[self.head]

    def Rear(self) -> int:
        return -1 if self.isEmpty() else self.buf[(self.head + self.count - 1) % len(self.buf)]

    def isEmpty(self) -> bool:
        return self.count == 0

    def isFull(self) -> bool:
        return self.count == len(self.buf)

複雜度
#

每個操作 O(1),空間 O(k)。

要特別避免的錯誤
#

  • 用 head 和 tail 兩個指標,卻沒有額外記錄數量:空和滿時兩個指標都相等,分不出來。
  • Rear 的位置忘記減 1。
  • 出隊時去清空陣列的值:不需要,之後寫入會直接覆蓋。

面試口說整理
#

我用一個大小為 k 的陣列,加上第一個元素的位置 head 和元素數量 count。入隊寫在 (head + count) % k,出隊把 head 往後移一格並取模,最後一個元素在 (head + count - 1) % k。空和滿直接看 count,所以不會有兩個指標重疊時的歧義。每個操作都是 O(1)。

相關文章

LeetCode 3829: Design Ride Sharing System
·1 分鐘
LeetCode Medium Queue Design Hash-Map Lazy-Deletion
LeetCode 3829 解題筆記:乘客和司機各一個 queue,取消只記在 set 裡,配對前再把隊頭已取消的乘客丟掉
LeetCode 307: Range Sum Query - Mutable
·2 分鐘
LeetCode Medium Segment-Tree Binary-Indexed-Tree Design Array
LeetCode 307 解題筆記:單點更新加區間和,前綴和每次更新要 O(n);用線段樹或 Fenwick Tree,兩種操作都是 O(log n)
LeetCode 281: Zigzag Iterator
·1 分鐘
LeetCode Medium Queue Design Iterator
LeetCode 281 解題筆記:queue 裡放還沒用完的來源,輪流取一個,還有剩就放回尾端;可以直接推廣到 k 個
LeetCode 1570: Dot Product of Two Sparse Vectors
·1 分鐘
LeetCode Medium Two-Pointers Design Hash-Table Array
LeetCode 1570 解題筆記:只存非零的 (index, value),內積時用雙指針合併兩個依 index 排序的列表,index 相同才相乘
LeetCode 3835: Count Subarrays With Cost Less Than or Equal to K
·1 分鐘
LeetCode Medium Sliding-Window Monotonic-Queue Queue Array
LeetCode 3835 解題筆記:花費 = (最大 - 最小) × 長度,視窗變大只會變貴,所以可以滑動視窗數子陣列;視窗最大、最小值用兩個單調佇列維護
LeetCode 244: Shortest Word Distance II
·1 分鐘
LeetCode Medium Two-Pointers Design Hash-Table String Array
LeetCode 244 解題筆記:預處理每個字的出現位置(天然排序),查詢時對兩個位置列表做雙指針合併,每次移動比較小的那個