LeetCode算法题python解法:23. Merge k Sorted Lists

Posted slarker

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode算法题python解法:23. Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。

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

题目大意就是给定多个已经排序的链表合并成一个排序的链表,我这里是将多个链表的值遍历添加到一个链表中,然后重新组织链表。复杂多比较高
代码如下:
class Solution:
    def mergeKLists(self, lists):
        if lists == []:
            return None
        link = []
        for i in lists:
            while i != None:
                link.append(i.val)
                if i.next == None:
                    break
                i = i.next
        link = sorted(link)
        print(link)
        if len(link) == 0:
            return None
        out = [ListNode(link[0])]
        for i in range(1, len(link)):
            out.append(ListNode(link[i]))
            out[i - 1].next = out[i]

        out.append(ListNode(link[-1]))
        return out[0]

 




以上是关于LeetCode算法题python解法:23. Merge k Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode算法题python解法:17. Letter Combinations of a Phone Number

LeetCode算法题python解法:25. Reverse Nodes in k-Group

LeetCode算法题-Move Zeroes(Java实现-三种解法)

LeetCode算法题-Valid Perfect Square(Java实现-四种解法)

LeetCode算法题-Power of Four(Java实现-六种解法)

LeetCode算法题-Find the Difference(Java实现-五种解法)