LeetCode 题解工作台
区间列表的交集
给定两个由一些 闭区间 组成的列表, firstList 和 secondList ,其中 firstList[i] = [start i , end i ] 而 secondList[j] = [start j , end j ] 。每个区间列表都是成对 不相交 的,并且 已经排序 。 返回这 两…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
class Solution: def intervalIntersection(
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定两个由一些 闭区间 组成的列表,firstList 和 secondList ,其中 firstList[i] = [starti, endi] 而 secondList[j] = [startj, endj] 。每个区间列表都是成对 不相交 的,并且 已经排序 。
返回这 两个区间列表的交集 。
形式上,闭区间 [a, b](其中 a <= b)表示实数 x 的集合,而 a <= x <= b 。
两个闭区间的 交集 是一组实数,要么为空集,要么为闭区间。例如,[1, 3] 和 [2, 4] 的交集为 [2, 3] 。
示例 1:
输入:firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]] 输出:[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
示例 2:
输入:firstList = [[1,3],[5,9]], secondList = [] 输出:[]
示例 3:
输入:firstList = [], secondList = [[4,8],[10,12]] 输出:[]
示例 4:
输入:firstList = [[1,7]], secondList = [[3,10]] 输出:[[3,7]]
提示:
0 <= firstList.length, secondList.length <= 1000firstList.length + secondList.length >= 10 <= starti < endi <= 109endi < starti+10 <= startj < endj <= 109endj < startj+1
解题思路
方法一:双指针
class Solution:
def intervalIntersection(
self, firstList: List[List[int]], secondList: List[List[int]]
) -> List[List[int]]:
i = j = 0
ans = []
while i < len(firstList) and j < len(secondList):
s1, e1, s2, e2 = *firstList[i], *secondList[j]
l, r = max(s1, s2), min(e1, e2)
if l <= r:
ans.append([l, r])
if e1 < e2:
i += 1
else:
j += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate understands how to implement a two-pointer technique efficiently.
- question_mark
They should be able to explain the trade-off of traversing both lists in a single pass rather than checking each pair of intervals individually.
- question_mark
The candidate can identify the necessary conditions for intervals to overlap and the corresponding actions to move the pointers accordingly.
常见陷阱
外企场景- error
Incorrectly handling cases where intervals do not overlap, resulting in missing intersections.
- error
Failing to move the correct pointer after finding an intersection, leading to unnecessary comparisons.
- error
Not keeping track of the current intersecting range properly, which could lead to incorrect results.
进阶变体
外企场景- arrow_right_alt
The problem can be extended to find the union of two interval lists instead of the intersection.
- arrow_right_alt
A variant could involve unsorted interval lists, requiring sorting before applying the two-pointer technique.
- arrow_right_alt
The problem could also ask to handle intervals with more complex ranges, such as half-open intervals.