839. 合并两个排序的间隔列表

839. 合并两个排序的间隔列表

中文English

合并两个已排序的区间列表,并将其作为一个新的有序区间列表返回。新的区间列表应该通过拼接两个列表的区间并按升序排序。

样例

样例1

输入: [(1,2),(3,4)] and list2 = [(2,3),(5,6)]
输出: [(1,4),(5,6)]
解释:
(1,2),(2,3),(3,4) --> (1,4)
(5,6) --> (5,6)

样例2

输入: [(1,2),(3,4)] 和 list2 = [(4,5),(6,7)]
输出: [(1,2),(3,5),(6,7)]
解释:
(1,2) --> (1,2)
(3,4),(4,5) --> (3,5)
(6,7) --> (6,7)

注意事项

同一个列表中的区间一定不会重叠。
不同列表中的区间可能会重叠。

"""
Definition of Interval.
class Interval(object):
    def __init__(self, start, end):
        self.start = start
        self.end = end
"""

class Solution:
    """
    @param list1: one of the given list
    @param list2: another list
    @return: the new sorted list of interval
    """
    '''
    大致思路:
    1.首先合并两个排序列表,要进行排序,给出一个排序合并列表的方法
    2.循环列表,初始化res = [],给定初始值start,end,当下一个元素和end无关联的时候,此时就为下一个需要append到res的数组
    关联条件:
    L[i][0] >= L
    注意:start,end是实时变化的,根据循环来变化
    3.跳出条件,循环结束,此时自动跳出,返回res
    '''
    def mergeTwoInterval(self,list1,list2):
        res = []
        L = self.getsortlist(list1,list2)
        strat = L[0][0]
        end = L[0][1]
        
        for i in range(1,len(L)):

            ##下一个数组和上一个数组关联条件
            if L[i][0] <= end:
                ##判断后缀
                if L[i][1] > L[i-1][1]:
                    end = L[i][1]
                ##否则后缀不变
            ##否则的话,不关联需要append到res里面
            else:    
                res.append((strat,end))
                strat = L[i][0]
                end = L[i][1]
        #最后的时候还需要append一下最后的值
        res.append((strat,end))
        return res
                

    def getsortlist(self,list1,list2):
        list1.extend(list2)
        for i in range(len(list1)):
            for j in range(i,len(list1)):
                if list1[i][0] > list1[j][0]:
                    temp = list1[j]
                    list1[j] = list1[i]
                    list1[i] = temp

        return list1
原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12567450.html