題目描述
給定一天的行事曆事件列表,輸出 Busy View:把所有重疊或相鄰的事件時間段合併成連續區間,不顯示單一事件細節。
每個事件包含開始時間、結束時間與標題(Busy View 不需要標題)。時間精度到分鐘。
範例
輸入事件:
(100, 300, "Event")
(115, 145, "Event")
(145, 215, "Event")
(200, 400, "Event")
(215, 230, "Event")
(215, 415, "Event")
(600, 700, "Event")
(500, 600, "Event")
輸出 Busy View:
(100, 415)
(500, 700)
解題思路
這是經典的區間合併:
- 依開始時間排序
- 逐一掃描,若與目前區間重疊或相鄰就合併
- 否則把目前區間收進結果並開新區間
Python 參考實作
def busy_view(events: list[tuple[int, int, str]]) -> list[tuple[int, int]]:
if not events:
return []
events.sort(key=lambda x: x[0])
res = []
cur_s, cur_e = events[0][0], events[0][1]
for s, e, _ in events[1:]:
if s <= cur_e:
cur_e = max(cur_e, e)
else:
res.append((cur_s, cur_e))
cur_s, cur_e = s, e
res.append((cur_s, cur_e))
return res
複雜度
- 時間:
O(n log n)(排序) - 空間:
O(n)(輸出)
需要面試輔助服務?聯絡 OA VO Service
- 📧 Email: [email protected]
- 📱 Phone: +86 17863968105
需要面試真題? 立刻聯繫微信 Coding0201,獲得真題。