首页 > 其他 > 详细

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

时间:2019-07-12 15:58:38      阅读:85      评论:0      收藏:0      [点我收藏+]

# 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
        

 

技术分享图片

 

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

原文:https://www.cnblogs.com/marvintang1001/p/11176216.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!