[LeetCode][python3]0023. Merge k Sorted Lists

class Solution(object):
def mergeKLists(self, lists):
l = []
for list_node in lists:
node = list_node
while node:
l.append(node)
node = node.next
if not l:
return None
l.sort(key=lambda x: x.val)
for i, node in enumerate(l):
if i == len(l)-1:
node.next = None
else:
node.next = l[i+1]
return l[0]
from heapq import heappop, heappush
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
dummy = cur = ListNode(0)
heap = []
for l in lists:
while l:
heappush(heap, l.val)
l = l.next
while heap:
cur.next = ListNode(heappop(heap))
cur = cur.next
return dummy.next
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
dic={}
for index,item in enumerate(lists):
if item != None:
dic[index]=item.val
h=p=ListNode()
while dic:
index,item=min(dic.items(),key= lambda a: a[-1])
p.next=ListNode(item)
p=p.next
lists[index]=lists[index].next
if lists[index]==None:
del dic[index]
else:
dic[index]=lists[index].val
h=h.next
return h

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store