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
相关推荐
web_1553427465627 分钟前
性能巅峰对决:Rust vs C++ —— 速度、安全与权衡的艺术
c++·算法·rust
计算机小白一个7 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
万事可爱^8 小时前
HDBSCAN:密度自适应的层次聚类算法解析与实践
算法·机器学习·数据挖掘·聚类·hdbscan
大数据追光猿9 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!10 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉10 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生10 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴10 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing10 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财10 小时前
加油站(力扣134)
算法·leetcode·职场和发展