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
相关推荐
bubiyoushang8886 分钟前
基于 TGLVM 算法的迁移学习分类系统
算法·分类·迁移学习
Rabitebla15 分钟前
深入理解 C++ STL:stack 和 queue 的底层原理与实现
c语言·开发语言·数据结构·c++·算法
通信仿真爱好者24 分钟前
【无标题】
人工智能·算法·机器学习
落羽的落羽35 分钟前
【算法札记】练习 | Week3
linux·服务器·数据结构·c++·人工智能·算法·动态规划
艾iYYY1 小时前
类和对象(详解初始化列表, static成员变量, 友元,内部类)
c语言·数据结构·c++·算法
AbandonForce1 小时前
C++11:列表初始化||右值和移动语义||引用折叠和完美转发||可变参数模板||lambda表达式||包装器(function bind)
开发语言·数据结构·c++·算法
khalil10201 小时前
代码随想录算法训练营Day-50 图论02 | 99.岛屿数量-深搜、99.岛屿数量-广搜 、100.岛屿的最大面积
数据结构·c++·算法·leetcode·深度优先·图论
Brilliantwxx1 小时前
【C++】模版进阶(特化+分离编译+非类型模版参数)
开发语言·数据结构·c++·算法
Black蜡笔小新1 小时前
自动化AI算法训练服务器DLTM企业级AI模型工作站构筑企业AI自主可控新模式
人工智能·算法·自动化
bnmoel1 小时前
数据结构深度剖析链表全集:结构实现、分类与底层原理全解析
c语言·数据结构·算法·链表·双向链表