5月挑战Day23-Interval List Intersections(Medium)

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:

leetcodeExample解释

解法:

原先想着暴力破解,之间遍历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

上面那个解析网站上说的时间复杂度为O(nm),这里我有点不一样的看法,我认为可能时间复杂度为O(m + n),因为首先就是一个while循环,虽然是两个判断条件但是这两条件应该是一个线性相加的关系而不是乘法关系。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值