← 返回博客列表
Bloomberg

Bloomberg 面試題:行事曆 Busy View 合併重疊時間區間

2025-12-15

題目描述

給定一天的行事曆事件列表,輸出 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)

解題思路

這是經典的區間合併

  1. 依開始時間排序
  2. 逐一掃描,若與目前區間重疊或相鄰就合併
  3. 否則把目前區間收進結果並開新區間

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

複雜度


需要面試輔助服務?聯絡 OA VO Service

需要面試真題? 立刻聯繫微信 Coding0201,獲得真題