Day 12 合并K个排序链表

合并K个排序链表

合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6

使用语言:Python3
方法:暴力法

# 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:
        re=[]
        for l in lists:
            while l:
                re.append(l.val)
                l=l.next
        re.sort()
        if not re:
            return None
        a=rel=ListNode(re[0])
        for i in range(1,len(re)):
            rel.next=ListNode(re[i])
            rel=rel.next
        return a

在这里插入图片描述
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-k-sorted-lists
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

发布了23 篇原创文章 · 获赞 0 · 访问量 223

猜你喜欢

转载自blog.csdn.net/Lester18/article/details/104825929