题目描述
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
题目理解
把链表都加入一个数组中,然后排序,再加到最后的链表中,算法复度为O(nlog(n))
代码实现
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
res = []
for i in lists:
while i :
res.append(i.val)
i = i.next
if res == []:
return []
res.sort()
l = ListNode(0)
first = l
while res:
l.next = ListNode(res.pop(0))
l = l.next
return first.next