Python solution leetcode:23. Merge k Sorted Lists

Source: Internet
Author: User

    • Title Description: Combine the list of K-sorted lists into a sort of chain table

    • Ideas:
    1. Use the heap sort, traverse the list, and place the value of the head pointer of the linked list and the head pointer itself as an element in the heap;
    2. After traversing the list in the first step, there is a maximum of n elements in the heap, and n is the length of the list;
    3. When the heap is not empty, remove the minimum value from the heap, then point the pointer to the next element and merge it into the heap;
    4. The 3rd step is to ensure that the heap is always O (n) size;
    5. The heap is empty to return the head node.
# Definition for singly-linked list.# class ListNode (object):# def __init__ (self, x):# self.val = x# self.next = NoneclassSolution (Object):defMergeklists ( Self, lists):""": Type Lists:list[listnode]: Rtype:listnode        """        ImportHEAPQ Min_heap=[] ret=Head=ListNode (0) forK, Linkinch Enumerate(lists):ifLink:heapq.heappush (Min_heap, [Link.val, link]) whileMin_heap:cur=Heapq.heappop (MIN_HEAP) ret.Next =cur[-1] Ret=Ret.Next            ifRet.Next: Heapq.heappush (Min_heap, [ret.Next. val, ret.Next])returnHead.Next

Python solution leetcode:23. Merge k Sorted Lists

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.