LeetCode——23.合并K个排序链表
原创
©著作权归作者所有:来自51CTO博客作者Nirvana柒的原创作品,请联系作者获取转载授权,否则将追究法律责任

题解
- 每次选取各个列表头中最小的元素加入到结果集中,时间复杂度:

- 选最小头的过程可以用优先队列优化,时间复杂度:

AC-Code
class Solution {
public:
struct Status {
int val;
ListNode *ptr;
bool operator < (const Status &rhs) const { // 优先队列将优先级最大的放前面
return val > rhs.val; // 实际上优先队列弹出最小
}
};
priority_queue <Status> q;
ListNode* mergeKLists(vector<ListNode*>& lists) {
for (auto node: lists) {
if (node) q.push({node->val, node});
}
ListNode head, *tail = &head;
while (!q.empty()) {
auto f = q.top(); q.pop();
tail->next = f.ptr;
tail = tail->next;
if (f.ptr->next) q.push({f.ptr->next->val, f.ptr->next});
}
return head.next;
}
};