Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
My code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists_my(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
#First we calculate it's length
count=len(lists)
for item in lists:
tmp=item
if tmp==None:
count-=1
continue
while tmp.next!=None:
tmp=tmp.next
count+=1
print(count)
if count==0:
return None
start_node=ListNode(0)
head=start_node
i=0
while i<count:
min_value=1000000000
for k in range(len(lists)):
tmp_node=lists[k]
if tmp_node!=None:
#print('check min value %d best node value %d' %(min_value,tmp_node.val))
if min_value>tmp_node.val:
use_node=lists[k]#Here you can not use tmp node, it's a pointer
min_value=lists[k].val
use_k=k
#print('min value %d best node value %d'%(min_value,use_node.val))
if i!=count-1:
start_node.val=min_value
tmp_node=ListNode(0)
start_node.next=tmp_node
start_node=tmp_node
use_node=use_node.next
lists[use_k]=use_node
else:
start_node.val=min_value
start_node.next=None
use_node=use_node.next
lists[use_k]=use_node
i=i+1
return head
def mergeKLists(self, lists):
allnodes=[]
for i in lists:
current = i
while(current!=None):
allnodes.append(current.val)
current=current.next
allnodes.sort()
return (allnodes)
Solution:
https://leetcode.com/problems/merge-k-sorted-lists/