leetcod hot 14-----100

在这里插入图片描述

class Solution(object):
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        self.nodes = []
        head = point = ListNode(0)
        for l in lists:
            while l:
                self.nodes.append(l.val)
                l = l.next
        for x in sorted(self.nodes):
            point.next = ListNode(x)
            point = point.next
        return head.next

在这里插入图片描述
分治:
将一个大问题分解成多个小问题来求解,在将小问题的解的和化为一起。
在这里插入图片描述

while interval < amount:
    for i in range(0, amount - interval, interval * 2):
        lists[i] = self.merge2Lists(lists[i], lists[i + interval])
    interval *= 2

分治的核心是这步代码,不理解就跑一遍,代入数据去验算就懂了。

class Solution(object):
    def mergeKLists(self, lists):
        amount = len(lists)
        interval = 1
        while interval < amount:
            for i in range(0, amount - interval, interval * 2):
                lists[i] = self.merge2Lists(lists[i], lists[i + interval])
            interval *= 2
        return lists[0] if amount > 0 else lists
    def merge2Lists(self, l1, l2):
        head = point = ListNode(0)
        while l1 and l2:
            if l1.val <= l2.val:
                point.next = l1
                l1 = l1.next
            else:
                point.next = l2
                l2 = l1
                l1 = point.next.next
            point = point.next
        if not l1:
            point.next=l2
        else:
            point.next=l1
        return head.next

在这里插入图片描述

发布了96 篇原创文章 · 获赞 1 · 访问量 1812
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览