视频讲解

合并k个已排序的链表

http://www.nowcoder.com/questionTerminal/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

视频链接:https://www.bilibili.com/video/BV1cK4y1Q7th/
归并排序思路

import sys
sys.setrecursionlimit(1000000)
class Solution:
    def mergeKLists(self , lists ):
        if not lists: return
        n = len(lists)
        return self.merge(lists, 0, n - 1)

    def merge(self, lists, left, right):
        if left == right: return lists[left]
        mid = left + (right - left) // 2
        list1 = self.merge(lists, left, mid)        
        list2 = self.merge(lists, mid+1, right)
        return self.mergeTwoLists(list1, list2)

    def mergeTwoLists(self, list1, list2):
        if not list1: return list2
        if not list2: return list1
        if list1.val < list2.val:
            list1.next = self.mergeTwoLists(list1.next, list2)
            return list1
        else:
            list2.next = self.mergeTwoLists(list2.next, list1)
            return list2
全部评论

相关推荐

我在朝九晚六双休的联想等你:如果我是你,身体素质好我会去参军,然后走士兵计划考研211只需要200多分。
点赞 评论 收藏
分享
评论
1
收藏
分享
牛客网
牛客企业服务