23. 合并K个排序链表
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6
通过次数
95,145
提交次数
190,901
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//小顶堆重载小于号
struct cmp{
bool operator ()(ListNode* const&a, ListNode* const&b){
return a->val>b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *ans = new ListNode(-1);//哑结点、哨兵
ListNode *tmp = ans;
priority_queue<ListNode *, vector<ListNode *>, cmp>q;
for(auto it:lists){
if(it)
q.push(it);
}
while(!q.empty()){
ListNode *topNode = q.top();
q.pop();
tmp->next = new ListNode(topNode->val);//等价于tmp->next = topNode
tmp = tmp->next;
if(topNode->next)
q.push(topNode->next);
}
return ans->next;
}
};
时间复杂度O(nlogK),空间复杂度O(n)
所得:
1.带哑结点的链表ans,指示结点tmp
2.常量指针与指针常量
3.优先队列重载小于号的两种方式