heap的使用——合并K个排序间隔列表,和merge K个有序数组是一样的

577. 合并K个排序间隔列表

中文
English

将K个排序的间隔列表合并到一个排序的间隔列表中,你需要合并重叠的间隔。

样例

样例1

输入: [
  [(1,3),(4,7),(6,8)],
  [(1,2),(9,10)]
]
输出: [(1,3),(4,8),(9,10)]

样例2

输入: [
  [(1,2),(5,6)],
  [(3,4),(7,8)]
]
输出: [(1,2),(3,4),(5,6),(7,8)]
"""
Definition of Interval.
class Interval(object):
    def __init__(self, start, end):
        self.start = start
        self.end = end
"""
import heapq


class Solution:
    """
    @param intervals: the given k sorted interval lists
    @return:  the new sorted interval list
    """
    def mergeKSortedIntervalLists(self, intervals):
        # write your code here
        def append(arr, l, r):
            if not arr:
                arr.append(Interval(l, r))
                return
            
            if arr[-1].start <= l <= arr[-1].end:
                arr[-1].end = max(r, arr[-1].end)
            else:
                arr.append(Interval(l, r))
        
        q = []
        for i,arr in enumerate(intervals):
            if arr:
                heapq.heappush(q, (intervals[i][0].start, intervals[i][0].end, i, 0))
        
        ans = []
        while q:
            l, r, i, j = heapq.heappop(q)
            append(ans, l, r)
            
            if j+1 < len(intervals[i]):
                heapq.heappush(q, (intervals[i][j+1].start, intervals[i][j+1].end, i, j+1))
                
        return ans
        

 

posted @ 2021-01-22 23:46  bonelee  阅读(142)  评论(0编辑  收藏  举报