码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-10-01 00:32:30      阅读:270      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   io   使用   ar   for   

原题地址: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]

标签:des   style   blog   http   color   io   使用   ar   for   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!