码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-10-09 13:59:10      阅读:342      评论:0      收藏:0      [点我收藏+]

标签:int   amp   turn   linked   val   class   python   链表   pre   

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

标签:int   amp   turn   linked   val   class   python   链表   pre   

原文地址:https://www.cnblogs.com/slarker/p/9759799.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!