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

LeetCode 253: Meeting Rooms II

·1 分鐘· ·
LeetCode Medium Heap Sorting Intervals Sweep-Line
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: medium 第一次嘗試:2026-10-15

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

需要的房間數 = 同一時間最多有幾場會議在進行。

依開始時間排序,用 min-heap 存「進行中會議的結束時間」。每場新會議開始前,先把已經結束的會議彈出,再把自己的結束時間推進去。過程中 heap 的最大長度就是答案。

我的第一版:< 應該是 <=
#

while heap and heap[0] < start:      # 結束時間 == 開始時間時沒有彈出
    heapq.heappop(heap)

會議是半開區間 [start, end):一場會議在 10 點結束,另一場 10 點開始,可以用同一間房間。所以結束時間等於開始時間時也要彈出,條件要用 <=。

正確解法
#

import heapq

class Solution:
    def minMeetingRooms(self, intervals: List[List[int]]) -> int:
        intervals.sort()
        heap = []
        best = 0
        for start, end in intervals:
            while heap and heap[0] <= start:
                heapq.heappop(heap)
            heapq.heappush(heap, end)
            best = max(best, len(heap))
        return best

原本另外用 count 記錄 heap 的大小,其實 len(heap) 就是。

另一種解法:開始和結束分開排序
#

class Solution:
    def minMeetingRooms(self, intervals: List[List[int]]) -> int:
        starts = sorted(s for s, _ in intervals)
        ends = sorted(e for _, e in intervals)
        rooms = best = j = 0
        for s in starts:
            while ends[j] <= s:          # 先釋放已經結束的
                rooms -= 1
                j += 1
            rooms += 1
            best = max(best, rooms)
        return best

複雜度
#

兩種解法都是時間 O(n log n),空間 O(n)。

要特別避免的錯誤
#

  • 半開區間用 <:同一時刻結束和開始的會議會被當成重疊。
  • 只看相鄰兩場會議有沒有重疊:要看的是「同時進行的數量」。

面試口說整理
#

需要的房間數是同時進行的會議的最大數量。我依開始時間排序,用 min-heap 存進行中會議的結束時間;每場會議開始前,先彈出結束時間小於等於它開始時間的會議,因為區間是半開的,剛好結束的房間可以重用。再把自己的結束時間推進去,heap 的最大長度就是答案。時間 O(n log n)。

相關文章

LeetCode 759: Employee Free Time
·1 分鐘
LeetCode Hard Heap K-Way-Merge Intervals Sweep-Line
LeetCode 759 解題筆記:用 K 路合併依開始時間掃過所有工作區間,目前最晚結束時間之後的空檔就是共同空閒
LeetCode 2054: Two Best Non-Overlapping Events
·1 分鐘
LeetCode Medium Dynamic-Programming Binary-Search Sorting Heap
LeetCode 2054 解題筆記:只能選兩個,所以對每個活動,加上「在它開始前就結束的活動裡價值最大的」;依結束時間排序,前綴最大值 + 二分搜尋
LeetCode 2402: Meeting Rooms III
·2 分鐘
LeetCode Hard Heap Sorting Simulation Intervals
LeetCode 2402 解題筆記:空閒房間和忙碌房間各一個 heap,延後的會議要保留原本的長度
LeetCode 1353: Maximum Number of Events That Can Be Attended
·1 分鐘
LeetCode Medium Heap Greedy Sorting
LeetCode 1353 解題筆記:每天參加「最早結束」的活動,用 min-heap 存結束日
LeetCode 2973: Find Number of Coins to Place in Tree Nodes
·2 分鐘
LeetCode Hard Dynamic-Programming Tree-Dp Depth-First-Search Sorting Heap Tree
LeetCode 2973 解題筆記:三個數的最大乘積只可能是「最大的三個」或「最小的兩個 × 最大的一個」;每個子樹只回傳最小 2 個和最大 3 個,後序合併
LeetCode 3961: Maximize Sum of Device Ratings
·1 分鐘
LeetCode Medium Greedy Sorting Matrix
LeetCode 3961 解題筆記:除了一台以外,每台把最小的單位捐給同一台;那台的評分變成全域最小值,挑第二小值最小的那台當接收者