首页 > 编程语言 > 详细

[leetcode]Merge k Sorted Lists @ Python [基础知识: heap]

时间:2014-09-30 23:34:40      阅读:430      评论:0      收藏:0      [点我收藏+]

原题地址:https://oj.leetcode.com/problems/merge-k-sorted-lists/

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

解题思路:

归并k个已经排好序的链表, 使用堆这一数据结构. 堆,也叫做:priority queue

首先将每条链表的头节点进入堆中.

然后将最小的弹出,并将最小的节点这条链表的下一个节点入堆,依次类推,最终形成的链表就是归并好的链表。

 

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

class Solution:
    # @param a list of ListNode
    # @return a ListNode
    def mergeKLists(self, lists):
        heap = []
        for head in lists:
            if head:
                heap.append((head.val, head))
        heapq.heapify(heap)
        dummy = ListNode(0)
        curr = dummy
        while heap:
            (val, node) = heapq.heappop(heap)
            curr.next = ListNode(val)
            curr = curr.next
            if node.next:
                heapq.heappush(heap, (node.next.val, node.next))
        return dummy.next
        #heapq.heappush(heap, item):  Push the value item onto the heap, maintaining the heap invariant.
        #heapq.heappop(heap):         Pop and return the smallest item from the heap, maintaining the heap invariant.
        #https://docs.python.org/2/library/heapq.html

 

[leetcode]Merge k Sorted Lists @ Python [基础知识: heap]

原文:http://www.cnblogs.com/asrman/p/4002791.html

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