0
点赞
收藏
分享

微信扫一扫

python 合并 K 个升序链表 多种解法

彩虹_bd07 2024-01-04 阅读 11

解法一:直接合并后排序

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def mergeKLists(lists):
    all_nodes = []
    for linked_list in lists:
        while linked_list:
            all_nodes.append(linked_list.val)
            linked_list = linked_list.next
    all_nodes.sort()
    
    dummy = ListNode(0)
    current = dummy
    for val in all_nodes:
        current.next = ListNode(val)
        current = current.next
    return dummy.next

解法二:使用优先队列(堆)

import heapq

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def mergeKLists(lists):
    heap = []
    for i, linked_list in enumerate(lists):
        if linked_list:
            heapq.heappush(heap, (linked_list.val, i, linked_list))
    
    dummy = ListNode(0)
    current = dummy
    while heap:
        val, index, node = heapq.heappop(heap)
        current.next = ListNode(val)
        current = current.next
        node = node.next
        if node:
            heapq.heappush(heap, (node.val, index, node))
    return dummy.next

举报

相关推荐

0 条评论