力扣986.区间列表的交集(自己复习所用)
考虑最小末端点,例如示例1中,最小末端点在A[0],那么因为两个列表中区间都不相交的缘故,A[0]只可能与B中的一个区间B[0]相交(否则B中区间会相交),那么A[0]在后续不可能与其他区间相交,则可以不再考虑(删去),此时就需要寻找下一个最小末端点,来继续上诉步骤。
为什么下一个最小末端点不是B[0]呢,因为可能存在下面这种情况:
因此代码如下:
class Solution:
def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
ret=[]
i=j=0 #双指针指向当前比较区间
while i<len(firstList) and j<len(secondList):
#找相交区间
start=max(firstList[i][0],secondList[j][0])
end=min(firstList[i][1],secondList[j][1])
if start<=end:
ret.append([start,end])
#找最小末端点存在的区间
if firstList[i][1]<secondList[j][1]:
i+=1
else:
j+=1
return ret