23. Merge k Sorted Lists

23. Merge k Sorted Lists

Hard

6875349Add to ListShare

You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.

Merge all the linked-lists into one sorted linked-list and return it.

 

Example 1:

Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation: The linked-lists are:
[
  1->4->5,
  1->3->4,
  2->6
]
merging them into one sorted list:
1->1->2->3->4->4->5->6

Example 2:

Input: lists = []
Output: []

Example 3:

Input: lists = [[]]
Output: []

 

Constraints:

  • k == lists.length
  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • -10^4 <= lists[i][j] <= 10^4
  • lists[i] is sorted in ascending order.
  • The sum of lists[i].length won't exceed 10^4.

我的思路 :参考:21. Merge Two Sorted Lists,将实现抽成方法循环调用,直到列表变成一个。时间复杂度: \sum_{i=0}^{k-1}(k-i)list[i].length 最坏约等于 O(kN),其中N是所有节点数量

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
            if l1 is None:
                return l2
            if l2 is None:
                return l1

            head_node = cur_node = None
            while l1 and l2:
                node = None
                if l1.val < l2.val:
                    node = l1
                    l1 = l1.next
                else:
                    node = l2
                    l2 = l2.next

                if head_node is None:
                    head_node = cur_node = node
                else:
                    cur_node.next = node
                    cur_node = node

            while l1:
                cur_node.next = l1
                cur_node = l1
                l1 = l1.next
            while l2:
                cur_node.next = l2
                cur_node = l2
                l2 = l2.next

            return head_node

        if lists is None or len(lists) <= 0:
            return None
        node = mergeTwoLists(lists[0], None)
        i = 1
        while i < len(lists):
            node = mergeTwoLists(node, lists[i])
            i += 1
        return node

参考答案  https://leetcode.com/problems/merge-k-sorted-lists/solution/

解法1:暴力排序 

时间:O(NlogN)  N is the total number of nodes.

空间:O(1)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
     def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: 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

解法3:优先队列

优先队列始终保持k个数,即k个列表当前的最小的数,即O(logk)

时间:O(Nlogk) k is the number of linked lists.

 

from Queue import PriorityQueue

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        head = point = ListNode(0)
        q = PriorityQueue()
        for l in lists:
            if l:
                q.put((l.val, l))
        while not q.empty():
            val, node = q.get()
            point.next = ListNode(val)
            point = point.next
            node = node.next
            if node:
                q.put((node.val, node))
        return head.next

解法4:和我的一样

解法5:优化了解法4,不从头开始一个个合并,而是采用2个一组合并,合并次数的时间复杂度直接降到O(logk)

即时间复杂度:O(Nlogk),其中N是每次合并时间复杂度是当前2个列表的节点数和

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值