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
相关推荐
地平线开发者8 小时前
mul 与 reduce_sum 的优化实例
算法·自动驾驶
坚持编程的菜鸟8 小时前
LeetCode每日一题——Pow(x, n)
c语言·算法·leetcode
csdn_aspnet8 小时前
分享MATLAB在数据分析与科学计算中的高效算法案例
算法·matlab·数据分析
白云千载尽9 小时前
moveit使用和机器人模型与状态--正向运动学和逆向运动学分析(四)
算法·机器人·逆运动学·moveit·正向运动学
我想吃余9 小时前
【0基础学算法】前缀和刷题日志(三):连续数组、矩阵区域和
算法·矩阵·哈希算法
2501_938773999 小时前
文档搜索引擎搜索模块迭代:从基础检索到智能语义匹配升级
人工智能·算法·搜索引擎
CS创新实验室9 小时前
典型算法题解:长度最小的子数组
数据结构·c++·算法·考研408
我有一些感想……9 小时前
浅谈 BSGS(Baby-Step Giant-Step 大步小步)算法
c++·算法·数论·离散对数·bsgs
麦麦大数据9 小时前
F042 A星算法课程推荐(A*算法) | 课程知识图谱|课程推荐vue+flask+neo4j B/S架构前后端分离|课程知识图谱构造
vue.js·算法·知识图谱·neo4j·a星算法·路径推荐·课程推荐
贝塔实验室10 小时前
LDPC 码的度分布
线性代数·算法·数学建模·fpga开发·硬件工程·信息与通信·信号处理