leetcode 23. Merge k Sorted Lists

一:题意

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

python实现

from Queue import PriorityQueue
class Solution(object):
    def mergeKLists(self, lists):
# ---------暴力法----------------------------------------------
        # 时间:O(N) + O(NlogN)
        # 空间:O(N)
        # self.nodes = []
        # head = point = ListNode(0)
        # for l in lists:
        #     while l:
        #         self.nodes.append(l.val)
        #         l = l.next
        # for x in sorted(self.nodes):  # 排序真好
        #     point.next = ListNode(x)
        #     point = point.next
        # return head.next
        
# -----------归并排序(把所有链表先合成一个,Leetcode 148. Sort List)-------
        # 时间:O(N) + O(NlogN)  还是不是最优的 
        # 空间:O(1)
        
# ---------优先队列或者最小堆------------------------------------------------
        # 时间:O(N) + O(NlogK)  不是最优的情况啊,空间还可以优化
        # 空间:O(N) + O(K)
#         head = p = ListNode(-1)        
#         q = PriorityQueue()
#         for L in lists: # 头结点
#             if L: q.put((L.val, L))  # (k个链表头结点的值,头结点)
        
#         while not q.empty():
#             val, node = q.get() # 取出并弹出来
#             p.next = ListNode(val)
#             p = p.next
#             node = node.next
#             if node: q.put((node.val, node))
        
#         return head.next
# ----------Merge with Divide And Conquer(升级的归并排序)-----------------------------
        # 时间:O(NlogK)  还是最优的情况啊
        # 空间:O(1)
        
        def merge(head1, head2): # 合并两个链表,有空链表时也可以!
            newHead = ListNode(-1)
            p = newHead
            while head1 and head2:
                if head1.val <= head2.val:
                    p.next = head1
                    p = p.next
                    head1 = head1.next
                else:
                    p.next = head2
                    p = p.next
                    head2 = head2.next
            
            if head1: p.next = head1
            if head2: p.next = head2
            
            return newHead.next
        
        n = len(lists)
        if n < 1: return None
        interval = 1 
        while interval < n:
            for i in range(0, n-interval, interval*2):  # 先两两合并
                lists[i] = merge(lists[i], lists[i+interval])
            
            interval *= 2  # 再四四合并,再八八合并
        
        return lists[0]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值