2018-10-21Merge K Sorted Lists

  1. Merge K Sorted Lists
    Merge k sorted linked lists and return it as one sorted list.
    LC: 23
    Analyze and describe its complexity.

Example
Given lists:

[
2->4->null,
null,
-1->null
],
return -1->2->4->null.

"""
Definition of ListNode
class ListNode(object):

    def __init__(self, val, next=None):
        self.val = val
        self.next = next
"""
import heapq
class Type:
    def __init__(self, li):
        self.li = li
    def __lt__(self, other):
        return self.li.val - other.li.val < 0 
    def __gt__(self, other):
        return self.li.val - other.li.val > 0        
    def __eq__(self, other):
        return self.li.val - other.li.val == 0
    
class Solution:
    """
    @param lists: a list of ListNode
    @return: The head of one sorted list.
    """
    def mergeKLists(self, lists):
        heap = []
        for li in lists:
            if not li:
                continue
            heapq.heappush(heap, Type(li))
        
        dummy = trav = ListNode(-1)
        while heap:
            li_type = heapq.heappop(heap)
            trav.next = li_type.li
            trav = trav.next
            li_type.li = li_type.li.next
            if li_type.li:
               heapq.heappush(heap, li_type) 
        return dummy.next
  • Time: O(nklog(k))
  • Space: O(k) for constructing priority queue
    Notes:
  1. I practiced constructing comparator here. It should be noted that heap queue is min heap. So it is fine if I am to sort ascending numbers.
  2. Another key point of this problem is to traverse linked list.
    • It is important to use dummy = ListNode(-1) and then return dummy.next at the end.
    • Also, it should be coupled with trav = dummy and traverse all linked lists.
  3. As mentioned in here, the operator module functions allow multiple levels of sorting. I could put (list.val, list) into heap queue so that heap is sorted by head node's value (ascending order).
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • <center>#1 Two Sum</center> link Description:Given an arr...
    铛铛铛clark阅读 6,687评论 0 3
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,358评论 0 33
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,195评论 0 10
  • 小凳子,整整齐,排排坐,我们来,听报告; 手机录,本子记,听与练,取真经,教宝宝; 晓丹丹,自驾车,接大咖,买午餐...
    clara_pp阅读 3,375评论 0 1
  • 太阳把阳光大把大把地倾洒在窗台上,东西两盆虎皮海棠争相斗艳,桔子树在阳光下绿得发亮,朱顶红正在忙着抽箭,山影冷眼一...
    香梅1阅读 1,450评论 0 1

友情链接更多精彩内容