合并K个排序链表
合并K个排序链表
描述
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
题解
使用heapq,但是ListNode没有比较函数,所以需要自行定义:
ListNode.__lt__ = lambda x, y: x.val < y.val
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
ListNode.__lt__ = lambda x, y: x.val < y.val
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
heap = []
for each_list in lists:
if each_list:
heapq.heappush(heap, each_list)
header = curr = ListNode(0)
while heap:
node = heapq.heappop(heap)
curr.next = ListNode(node.val)
curr = curr.next
node = node.next
if node:
heapq.heappush(heap, node)
return header.next
题解2
不定义ListNode.__lt__
,在heappush的时候第一个为node.val,当val相等时,需要提供一个可比较的值,否则ListNode不可比较会报错,在此第二个数设置id,或者其他编号也可以
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists: List[ListNode]) -> ListNode:
heap = []
for each_list in lists:
if each_list:
heapq.heappush(heap, (each_list.val, id(each_list), each_list))
header = curr = ListNode(0)
while heap:
val, id_list, node = heapq.heappop(heap)
curr.next = ListNode(val)
curr = curr.next
node = node.next
if node:
heapq.heappush(heap, (node.val, id_list, node))
return header.next