Python 练习题(一)【python-leetcode42-区间合并】区间列表的交集

问题描述

  给定两个由一些闭区间组成的列表,每个区间列表都是成对不相交的,并且已经排序。返回这两个区间列表的交集。

  (形式上,闭区间 [a, b](其中 a <= b)表示实数 x 的集合,而 a <= x <= b。两个闭区间的交集是一组实数,要么为空集,要么为闭区间。例如,[1, 3] 和 [2, 4] 的交集为 [2, 3]。)

 

 

 

示例

输入:
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]]
注意:输入和所需的输出都是区间对象组成的列表,而不是数组或列表。

提示:

0 <= A.length < 1000
0 <= B.length < 1000
0 <= A[i].start, A[i].end, B[i].start, B[i].end < 10^9
 

代码

class Solution:
    def intervalIntersection(self, A: List[List[int]], B: List[List[int]]) -> List[List[int]]:
        ans = []
        i1, i2 = 0, 0
        while i1 < len(A) and i2 < len(B):
            left = max(A[i1][0], B[i2][0])
            right = min(A[i1][1], B[i2][1])
            if left <= right:
                ans.append([left, right])

            if A[i1][1] < B[i2][1]:
                i1 += 1
            else:
                i2 += 1

        return ans

核心就是标红的一段:比如

A = [[0,2],[5,10],[13,23],[24,25]]
B = [[1,5],[8,12],[15,24],[25,26]]

[0,2]和[1,5]之间2比5小,那么A中的下一个数组就可能与[1,5]有交集,所以让指向A的指针+1。反之让指向B的指针+1.

结果:

思路

由于区间已经排好序,所以先拿出A中的第一个区间和B中第一个区间,判断有没有交集,选取左端点的最大值作为start和右端点的最小值作为end,如果start<=end,那么就存在交集,将其放到结果文件中,然后判断A中的第一个区间和B中第一个区间那一个比较长,也就是右端点哪一个较大,如果A大,那么选取B的下一个,如果B大,那么选取A的下一个,依次比较即可.

def intersect(A,B):
    m = len(A)
    n = len(B)
    p1 = 0
    p2 = 0
    intersect = []
    while p1 < m and p2 < n:
        achr = A[p1][0]
        a1 = A[p1][1]
        a2 = A[p1][2]
        gene = A[p1][3]
        bchr = B[p1][0]
        b1 = B[p2][1]
        b2 = B[p2][2]

        start = max(a1, b1)
        end = min(a2, b2)
        if achr== bchr and start <= end:
            intersect.append([start, end, gene])
        if a2 < b2:
            p1 += 1
        else:
            p2 += 1
    return intersect

 

posted @ 2021-12-06 15:07  PythonGirl  阅读(375)  评论(0编辑  收藏  举报