LeetCode 0023. 合并 K 个升序链表

【LetMeFly】23.合并 K 个升序链表

力扣题目链接:https://leetcode.cn/problems/merge-k-sorted-lists/

给你一个链表数组,每个链表都已经按升序排列。

请你将所有链表合并到一个升序链表中,返回合并后的链表。

示例 1:

复制代码
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
  1->4->5,
  1->3->4,
  2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6

示例 2:

复制代码
输入:lists = []
输出:[]

示例 3:

复制代码
输入:lists = [[]]
输出:[]

提示:

  • k == lists.length
  • 0 <= k <= 10^4
  • 0 <= lists[i].length <= 500
  • -10^4 <= lists[i][j] <= 10^4
  • lists[i]升序 排列
  • lists[i].length 的总和不超过 10^4

方法一:优先队列

我们只需要将每个链表的 当前节点(初始值是表头) 放入小根堆中,每次从小根堆中取出一个节点并拼接起来,若这个节点不是表尾节点,则这个节点的下一个节点入队。

  • 时间复杂度 O ( N × log ⁡ k ) O(N\times \log k) O(N×logk),其中 n n n是所有节点的个数
  • 空间复杂度 O ( k ) O(k) O(k)

AC代码

C++

cpp 复制代码
class Solution {
private:
    struct cmp {
        bool operator() (const ListNode* a, const ListNode* b) {
            return a->val > b->val;
        }
    };
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*, vector<ListNode*>, cmp> pq;
        for (ListNode*& node : lists) {
            if (node) {
                pq.push(node);
            }
        }
        ListNode* head = new ListNode(), *p = head;
        while (pq.size()) {
            ListNode* thisNode = pq.top();
            pq.pop();
            p->next = thisNode;
            p = thisNode;
            if (thisNode->next) {
                pq.push(thisNode->next);
            }
        }
        return head->next;
    }
};

Python

python 复制代码
# from typing import List, Optional
# import heapq

# # Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

# ListNode.__lt__ = lambda a, b: a.val < b.val

class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        pq = []
        for node in lists:
            if node:
                heapq.heappush(pq, node)
        head = ListNode()
        p = head
        while pq:
            thisNode = heapq.heappop(pq)
            p.next = thisNode
            p = thisNode
            if thisNode.next:
                heapq.heappush(pq, thisNode.next)
        return head.next

同步发文于CSDN,原创不易,转载请附上原文链接哦~

Tisfy:https://letmefly.blog.csdn.net/article/details/132243952

相关推荐
艾莉丝努力练剑1 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途2 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
珊瑚里的鱼6 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
秋说7 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法
lifallen7 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka
liupenglove7 小时前
自动驾驶数据仓库:时间片合并算法。
大数据·数据仓库·算法·elasticsearch·自动驾驶
python_tty8 小时前
排序算法(二):插入排序
算法·排序算法
然我9 小时前
面试官:如何判断元素是否出现过?我:三种哈希方法任你选
前端·javascript·算法
F_D_Z9 小时前
【EM算法】三硬币模型
算法·机器学习·概率论·em算法·极大似然估计
秋说9 小时前
【PTA数据结构 | C语言版】字符串插入操作(不限长)
c语言·数据结构·算法