topic:
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
ListNode class has been defined
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
Ideas:
A method of traversing each link, each record has several different, then these numbers form a new chain
Method two, each link current digital comparator
Method three, two chains all combined, a final composite strand
Code:
method one:
import collections
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
nums = collections.defaultdict(lambda: 0)
for node in lists:
while node:
nums[node.val] += 1
node = node.next
node = ListNode(0)
start = node
keys = sorted(nums.keys())
for key in keys:
for i in range(nums[key]):
node_next = ListNode(key)
node.next = node_next
node = node_next
return start.next
Method Two:
def get_min_node(self,nodes):
# 选取value最小的node
val_min = 2**31
for node in nodes:
if node.val < val_min:
val_min = node.val
mini_node = node
return mini_node
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
start = ListNode(0)
temp_n = start
nodes = []
for node in lists:
if node:
nodes.append(node)
while len(nodes)>0:
node = self.get_min_node(nodes)
temp_n.next = node
temp_n = node
nodes.remove(node)
if node.next:
nodes.append(node.next)
return start.next
Method three: twenty-two merger
def merge2Lists(self,list1:ListNode,list2:ListNode):
if list1 and list2:
if list1.val < list2.val:
current = list1
other = list2
else:
current = list2
other = list1
start = current
prev = current
while current and other:
if current.val <= other.val:
prev = current
current = current.next
else:
prev.next = other
prev = other
other = current
current = prev.next
if current:
prev.next = current
elif other:
prev.next = other
return start
elif list1:
return list1
elif list2:
return list2
else:
return None
def mergeKLists(self, lists) -> ListNode:
while len(lists)>=2:
list1 = lists.pop()
list2 = lists.pop()
node_list = self.merge2Lists(list1,list2)
lists.insert(0,node_list)
if lists:
return lists[0]