【leetcode刷题日记】Task11-合并K个排序链表

题目描述

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

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

解题思路

  • 暴力法:依次合并两个有序链表,这样k个排序链表的合并问题就转化成了一个递归问题
# 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:
        def mergeTwoLists(l1,l2):
            pre = ListNode(None)
            head = pre
            while l1 and l2:
                if l1.val <= l2.val:
                    pre.next = l1
                    l1 = l1.next
                    pre = pre.next
                else:
                    pre.next = l2
                    l2 = l2.next
                    pre = pre.next
            pre.next = l1 if l1 else l2
            return head.next
        if not lists:
            return
        r = lists[0]
        for i in range(1,len(lists)):
            r = mergeTwoLists(r,lists[i])
        return r

在这里插入图片描述

  • 归并法:在暴力法的基础上进行改进,就是两两合并最后再一起合并,减少时间复杂度
# 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:
        def mergeTwoLists(l1,l2):
            pre = ListNode(None)
            head = pre
            while l1 and l2:
                if l1.val <= l2.val:
                    pre.next = l1
                    l1 = l1.next
                    pre = pre.next
                else:
                    pre.next = l2
                    l2 = l2.next
                    pre = pre.next
            pre.next = l1 if l1 else l2
            return head.next
        if not lists:
            return
        s = 1 #代表当前合并的两个链表的索引差
        n = len(lists)
        while s < n:
            for i in range(0,n,2 * s):
                if i + s <= n - 1:
                    lists[i] = mergeTwoLists(lists[i],lists[i + s])
            s *= 2
        return lists[0]

在这里插入图片描述

总结

  • 感觉对于刷题总是只能想出暴力解法,可能没有把真正的算法运用到解题中,希望继续加油,把算法真正的运用到解题中
发布了45 篇原创文章 · 获赞 2 · 访问量 1247

猜你喜欢

转载自blog.csdn.net/soulmate______/article/details/104815672