题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ #include <list> #include <memory> #include <numeric> #include <queue> #include <utility> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类vector * @return ListNode类 */ ListNode* mergeKLists(vector<ListNode*>& lists) { // 需要先过滤一下内容,将空东西处理掉 auto cmp = [](ListNode * v1, ListNode * v2) { return v1->val > v2->val; }; std::priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> pq(cmp); for(auto* li : lists) { if(li) pq.push(li); } auto root = std::make_unique<ListNode>(0); auto cur = root.get(); while (not pq.empty()) { auto node = pq.top(); pq.pop(); cur->next = node; cur = node; if (node->next) { pq.push(node->next); } } return root->next; } };