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