Original title address: https://oj.leetcode.com/problems/merge-k-sorted-lists/
Test instructions: Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Problem Solving Ideas:
Merge K's already sequenced list, using the data structure of the heap. Heap, also called: Priority queue
The head node of each linked list is first entered into the heap.
Then the smallest popup, and the smallest node in the list of the next node into the heap, and so on, and so on, the final form of the linked list is a well-merged linked list.
#Definition for singly-linked list.#class ListNode:#def __init__ (self, x):#self.val = x#Self.next = NoneclassSolution:#@param a list of ListNode #@return a ListNode defmergeklists (self, lists): Heap= [] forHeadinchlists:ifHead:heap.append ((Head.val, head)) heapq.heapify (heap) dummy=listnode (0) Curr=Dummy whileHeap: (Val, node)=heapq.heappop (heap) Curr.next=ListNode (val) Curr=Curr.nextifNode.next:heapq.heappush (Heap, (Node.next.val, Node.next))returnDummy.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 [Basics: Heap]