首页 > 编程语言 > 详细

[leetcode]Merge k Sorted Lists @ Python

时间:2014-06-11 21:55:41      阅读:480      评论: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个已经排好序的链表。使用堆这一数据结构,首先将每条链表的头节点进入堆中,然后将最小的弹出,并将最小的节点这条链表的下一个节点入堆,依次类推,最终形成的链表就是归并好的链表。

代码:

bubuko.com,布布扣
# 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 node in lists:
            if node: 
                heap.append((node.val, node))
        heapq.heapify(heap)
        head = ListNode(0); curr = head
        while heap:
            pop = heapq.heappop(heap)
            curr.next = ListNode(pop[0])
            curr = curr.next
            if pop[1].next: 
                heapq.heappush(heap, (pop[1].next.val, pop[1].next))
        return head.next
bubuko.com,布布扣

 

[leetcode]Merge k Sorted Lists @ Python,布布扣,bubuko.com

[leetcode]Merge k Sorted Lists @ Python

原文:http://www.cnblogs.com/zuoyuan/p/3772372.html

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