代码练习4-合并 k 个升序的链表。

数据范围:节点总数 0≤𝑛≤5000,每个节点的val满足 ∣𝑣𝑎𝑙∣<=1000

要求:时间复杂度 O(nlogn)

输入:[{1,2,3},{4,5,6,7}]

输出:{1,2,3,4,5,6,7}

C++核心代码

#include <vector>
#include <queue>

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
public:
    struct compare {
        bool operator()(ListNode* a, ListNode* b) {
            return a->val > b->val;  // 优先队列中小的优先
        }
    };
    
    ListNode* mergeKLists(std::vector<ListNode*>& lists) {
        // 创建一个优先队列(最小堆)
        std::priority_queue<ListNode*, std::vector<ListNode*>, compare> pq;
        
        // 将每个链表的头节点加入优先队列
        for (auto list : lists) {
            if (list) {
                pq.push(list);
            }
        }
        
        // 创建一个虚拟头节点
        ListNode dummy(0);
        ListNode* current = &dummy;
        
        // 合并链表
        while (!pq.empty()) {
            // 获取最小节点并将其从堆中移除
            ListNode* node = pq.top();
            pq.pop();
            
            // 将最小节点添加到结果链表中
            current->next = node;
            current = current->next;
            
            // 将下一节点加入堆中
            if (node->next) {
                pq.push(node->next);
            }
        }
        
        // 返回合并后的链表的头节点
        return dummy.next;
    }
};

Python核心代码

import heapq
from typing import List

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        # 定义一个最小堆
        heap = []
        
        # 将所有链表的头节点放入堆中
        for l in lists:
            if l:
                heapq.heappush(heap, (l.val, l))
        
        # 创建一个虚拟头节点
        dummy = ListNode(0)
        current = dummy
        
        # 合并链表
        while heap:
            val, node = heapq.heappop(heap)
            current.next = node
            current = current.next
            if node.next:
                heapq.heappush(heap, (node.next.val, node.next))
        
        return dummy.next

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值