Merge k Sorted Lists

本文介绍如何将多个已排序的链表合并成一个有序链表,通过反复合并相邻链表直至只剩一个,使用辅助函数mergelists进行节点比较和合并。时间复杂度为O(nlog(k)),空间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

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: []

Intuition

The given problem requires merging k sorted linked lists into a single sorted linked list. One way to approach this problem is to repeatedly merge pairs of linked lists until there is only one linked list remaining.

Approach

The mergeKLists function takes a list of linked lists as input.
It repeatedly merges pairs of linked lists until there is only one linked list remaining in the list.
The mergelists function is a helper function that merges two sorted linked lists. It iterates through the nodes of both lists, comparing the values, and building a new sorted list.
The merged lists are stored in the mergelist variable, and the process is repeated until there is only one list left.
The final merged list is returned.

Complexity

  • Time complexity:

The time complexity is O(n log(k)), where n is the total number of nodes across all lists, and k is the number of lists.

  • Space complexity:

The space complexity is O(1) as we use only a constant amount of extra space.

Code

# 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[Optional[ListNode]]) -> Optional[ListNode]:
        if not lists or len(lists) == 0:
            return None

        while len(lists) > 1:
            mergelist = []

            for i in range(0 , len(lists) , 2):
                l1 = lists[i]
                l2 = lists[i + 1] if i + 1 < len(lists) else None
                mergelist.append(self.mergelists(l1 , l2))

            lists = mergelist

        return lists[0]


    def mergelists(self, l1, l2):
        current = dummy = ListNode()

        while l1 and l2:
            if l1.val < l2.val:
                current.next = l1
                l1 = l1.next
            else:
                current.next = l2
                l2 = l2.next

            current = current.next

        if l1 or l2:
            current.next = l1 if l1 else l2
        
        return dummy.next
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值