[Leetcode] Merge k Sorted Lists @ Python [Basics: Heap]

Source: Internet
Author: User

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]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.