[leetcode]Merge k Sorted Lists @ Python


原題地址: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個已經排好序的鏈表。使用堆這一數據結構,首先將每條鏈表的頭節點進入堆中,然后將最小的彈出,並將最小的節點這條鏈表的下一個節點入堆,依次類推,最終形成的鏈表就是歸並好的鏈表。

代碼:

# 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM