# | 标题 | 难度 |
986 | 区间列表的交集 | M |
题目986
输入:A = [[0,2],[5,10],[13,23],[24,25]], B = [[1,5],[8,12],[15,24],[25,26]]
输出:[[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]]
注意:输入和所需的输出都是区间对象组成的列表,而不是数组或列表。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/interval-list-intersections
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
小结:时间复杂度O(m + n)
class Solution(object):
def intervalIntersection(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
an = len(A)
bn = len(B)
i = j = 0
res = []
while i < an and j < bn:
if A[i][1] < B[j][0]:
i += 1
elif A[i][0] > B[j][1]:
j += 1
elif A[i][1] > B[j][1]:
tmp_l = max(A[i][0], B[j][0])
res.append([tmp_l, B[j][1]])
j += 1
else:
tmp_l = max(A[i][0], B[j][0])
res.append([tmp_l, A[i][1]])
i += 1
return res