Day23-Interval List Intersections(Medium)
问题描述:
Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order.
Return the intersection of these two interval lists.
(Formally, a closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. The intersection of two closed intervals is a set of real numbers that is either empty, or can be represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3].)
两个列表表示数字的间隔,而我们要从中找出交集,就是[1,3],[2,4]的交集就是[2,3].
Example:
解法:
原先想着暴力破解,之间遍历A,然后让A和B中所有的数组进行求交集,但是考虑的情况似乎有点多,绕着绕着就把自己绕蒙了。
看了网上的解析后才知道原来可以用双指针来求解。
具体的图文解释可以看这个网站
上面这个网站给出了C++的写法,我在这里贴上python的写法以及我对这道题的理解。其实就是用两个指针分别从两个列表的头部开始遍历,如果两个指针没有相交,我们就舍弃在前面的列表,将那个列表的指针向后移动一位,如果相交我们就想结果列表中添加起点大的为结果位置的起点以及终点位置小的为结果位置的重点。
class Solution:
def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
result = []
if not A or not B:
return []
i,j = 0, 0
while i < len(A) and j < len(B):
a = A[i]
b = B[j]
if a[1] < b[0]:
i += 1
elif a[0] > b[1]:
j += 1
else:
result.append([max(a[0],b[0]),min(a[1],b[1])])
if a[1] <= b[1]:
i += 1
else:
j += 1
return result