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 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。