题解 | 合并k个已排序的链表
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <algorithm>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 可以利用现有
*
* @param lists ListNode类vector
* @return ListNode类
*/
static bool compareLess(ListNode* l1, ListNode* l2) {
return l1->val > l2->val;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
// write code here
ListNode fake(0);
ListNode *cur = &fake;
vector<ListNode*> vec;
for (auto & item : lists) {
if (item) {
vec.emplace_back(std::move(item));
}
}
make_heap(vec.begin(), vec.end(), compareLess);
while(vec.size()) {
cur->next = vec.front();
pop_heap(vec.begin(), vec.end(), compareLess);
vec.pop_back();
cur = cur->next;
if (cur->next) {
vec.push_back(cur->next);
push_heap(vec.begin(), vec.end(), compareLess);
}
}
return fake.next;
}
};

