150強訪談簡單

插入間隔

“插入間隔”問題的詳細指南和 Python 實作。

問題陳述

簡單

給定一個不重疊的間隔數組,其中間隔[i] = [starti, endi] 表示第 i 個間隔的開始和結束,並且間隔按 starti 升序排序。您也會得到一個間隔 newInterval = [start, end],表示另一個間隔的開始和結束。將 newInterval 插入間隔,使得間隔仍然按 starti 升序排序,並且間隔仍然沒有任何重疊間隔(如有必要,合併重疊間隔)。

返回插入後的間隔。

寫一個函數 insert(intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]

約束條件
  • 0 <= len(intervals) <= 10^4
  • intervals[i].length == 2
  • 0 <= starti <= endi <= 10^5
  • intervals is sorted by starti in ascending order
  • newInterval.length == 2
  • 0 <= start <= end <= 10^5

範例

Example 1
Input
intervals = [[1,3],[6,9]], newInterval = [2,5]
Output
[[1,5],[6,9]]
Explanation

The new interval [2,5] overlaps with [1,3], so they are merged into [1,5].

Example 2
Input
intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output
[[1,2],[3,10],[12,16]]
Explanation

Because [4,8] overlaps with [3,5],[6,7],[8,10], they merge to [3,10].

Need a Hint?
考慮使用特定於間隔的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。