Merge k Sorted Lists

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
相关推荐
2501_924877358 分钟前
智慧零售漏扫率↓79%!陌讯多模态融合算法在智能收银与货架管理的实战解析
大数据·人工智能·算法·目标检测·边缘计算·零售
爱编程的鱼1 小时前
C# 数组&C# 多维数组
数据结构·算法·c#
前端开发工程师请求出战1 小时前
MCP — 让AI变得更“百搭”
算法
人机与认知实验室2 小时前
人机环境空战矩阵
人工智能·线性代数·算法·机器学习·矩阵
百度Geek说2 小时前
5个技巧让文心快码成为你的后端开发搭子
后端·算法
上海迪士尼352 小时前
除自身以外数组的乘积是什么意思
数据结构·算法
数据智能老司机2 小时前
Python 实战遗传算法——遗传算法导论
python·算法·机器学习
咩?2 小时前
支持向量机(第二十九节课内容总结)
算法·机器学习·支持向量机
EulerBlind3 小时前
【机器学习】从KNN算法到图像风格迁移:原理与实践
人工智能·算法·机器学习
anscos3 小时前
设计仿真 | 从物理扫描到虚拟检具:Simufact Welding革新汽车零部件检测
人工智能·算法·汽车·软件