22. Merge k Sorted Lists Leetcode Python

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

假设平均linklist长度为m

1. 用一个hashtable 将k 个linklist的头存进去需要 k 

2.将hashtable里面的node的最小依次取出来加到新的Linklist后面。

需要将整个Linklist遍历一遍时间复杂度为O(km) 空间复杂度为O(k) 因为每次都只保留头

1. hash the k linklist with node.val as the key and node as the value

2.append the node with smallest value to the new linklist

we need to go through the whole linklist so the the time complexity if O(km) space is O(k) because we only preserve the head

# 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):
        if not lists:
            return None
        dummy=ListNode(0)
        l1=collections.defaultdict(list)
        for i in lists:
            if i:
                l1[i.val].append(i)
        cur=dummy
        while l1:
            minval=min(l1)
            node=l1[minval].pop()
            if l1[minval]==[]:
                del l1[minval]
            cur.next=node
            cur=cur.next
            if node.next==None:
                continue
            l1[node.next.val].append(node.next)
        return dummy.next
        


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值