【leetcode刷题笔记】023.Merge k Sorted Lists

日期:20180913
题目描述:

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
详解:

Approach: Merge with Divide And Conquer

Intuition & Algorithm

This approach walks alongside the one above but is improved a lot. We don't need to traverse most nodes many times repeatedly

  • Pair up k lists and merge each pair.
  • After the first pairing,k lists are merged into k/2 lists with average 2N/k length, then k/4, k/8 and so on.
  • Repeat this procedure until we get the final sorted linked list.

Thus, we'll traverse almost N nodes per pairing and merging, and repeat this procedure about log2k times.

Divide_and_Conquer
class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        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

整体思路是先合并两个链表,然后对于k个链表两两合并。合并两个链表,可以用递归,也可以想上面的代码一样采用牺牲头结点的方法,之前已经讲过构造链表牺牲头结点的方法了,这里不再赘述。

有的时候写循环体里面还有判断的时候会把自己绕糊涂,我有一个笨方法不过挺管用,就是现在草纸上把代码一行一行写出来,不用循环体,手动模拟循环的过程,最后看哪几行代码从何处开始重复,就把代码结构捋清了。不知道这么笨的方法是不是只有我一个人用。。。。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 有时候心情受人影响 觉得和不喜欢的人就应该保持距离甚至想无视 但却抬头不见低头见 改变不了的事实就要改变态度 是你...
    口吕品阅读 286评论 0 0
  • 外公是老公的外公,今年九十多岁的高龄,具体九十几岁,至今老公和我都不清楚。自嫁给老公那时起,就知道他的外公九十多岁...
    霁月霏阅读 271评论 0 1
  • 昨天周日,下午无聊的躺在床上,突然觉得我该做点什么,一窜而起马上穿了运动鞋就出门跑步了。 因为我住在深大边上,一直...
    粉蓝阅读 344评论 0 1
  • 他上过战场 战友们 都没有再起来 唯独他 活了下来 她患了不治不症 病友们一个个走了 她挺了过来 …… …… ...
    雪莉诗话阅读 424评论 9 14