23.合并K个排序链表

难度:困难
题目描述:
23.合并K个排序链表_第1张图片
思路总结

  1. 个人的想法很简单,借用21.合并两个有序链表的代码,结果当然是超时了。万恶的131个用例中的最后一个。虽然我的题解不堪重用,但是拿出来,复习一下合并两个有序链表的思想还是可以的。
  2. 这题没要求在原来的链表上操作,因此可以先取值,然后排序,最后在生成链表,有点暴力。

题解一:

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        #思路:立即想到了两两合并,因为之前做过两两合并的题。
        if not lists:return None
        def mergeTwoLists(l1, l2):
            #思路:递归,属实精彩。
            if not l1:return l2
            elif not l2:return l1
            elif l1.val < l2.val:
                l1.next = mergeTwoLists(l1.next, l2)
                return l1
            else:
                l2.next = mergeTwoLists(l1, l2.next)
                return l2
        l1 = lists[0]
        for i in range(1, len(lists)):
            l2 = lists[i]
            l1 = mergeTwoLists(l1, l2)
        return l1

题解一结果:
23.合并K个排序链表_第2张图片
题解二:

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        #思路:这题没要求在原来的链表上操作,因此可以先取值,然后排序,最后在生成链表,有点暴力。
        lists_val = []
        for i in range(len(lists)):
            cur = lists[i]
            while cur:
                lists_val.append(cur.val)
                cur = cur.next
        cur = ListNode(0)
        head = cur
        for i in sorted(lists_val):
            cur.next = ListNode(i)
            cur = cur.next
        return head.next

题解二结果:
在这里插入图片描述

你可能感兴趣的:(朱滕威的面试之路)