数据结构与算法之三——双指针

#标题难度
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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值