leetcode--23:(堆)Merge k Sorted Lists

# 2019.7.12:

我的思路:

  方法一:两两合并,用的是链表的方法:https://www.cnblogs.com/marvintang1001/p/11173546.html

  方法二:用堆的办法, 用python内置的heapq模块实现堆,heapq只能实现最小堆:https://www.jianshu.com/p/e003872fa7b9

      用heap.heapify(list) 构建最小堆;

      用heap.heappop(heap) 获取堆中的最小值。

      构建一个链表,并且返回这个链表的头节点

 

我的答案:(方法二)

from heapq import heapify, heappop

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        h = []
        for node in lists:
            while node:
                h.append(node.val)
                node = node.next
                
        if len(h) == 0:
            return h
        
        heapify(h)  # 原地建堆

        root = ListNode(heappop(h))
        cur = root
        while h:
            node = ListNode(heappop(h))
            cur.next = node
            cur = node
        return root
        

 

 

posted @ 2019-07-12 15:14  Marvin_Tang  阅读(216)  评论(0编辑  收藏  举报