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]
原文地址:https://www.cnblogs.com/slarker/p/9759799.html
时间: 2024-10-09 12:39:16