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

[leetcode]Merge k Sorted Lists @ Python

时间:2014-06-11 21:57:07      阅读:399      评论:0      收藏:0      [点我收藏+]

标签:des   style   class   blog   code   java   

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

标签:des   style   class   blog   code   java   

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

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