合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:简单的说就是建立一个堆,这个堆是排序的。使用Python库
在这里插入代# 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:
import heapq
dummy = ListNode(0)
p =start
head = []
for i in range(len(lists)):
if lists[i] :
heapq.heappush(head,(lists[i].val,i))
lists[i] = lists[i].next
while head :
val,idx = heapq.heappop(head)
p.next = ListNode(val)
p = p.next
if lists[idx] :
heapq.heappush(head,(lists[idx].val,idx))
lists[idx] = lists[idx].next
return start.next
码片
来源:CSDN
作者:晨光`
链接:https://blog.csdn.net/weixin_44268116/article/details/104444404