标签:pre com nal empty solution next describe val struct
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6]
Output: 1->1->2->3->4->4->5->6
//k个链表先丢进堆去,使用最小堆,我们取出最小那个,再放回去next结点,直到堆为空
//为此,我们需要为堆修改比较规则
//
struct cmp {//默认是最大堆,也就是使用了<,因此,我们修改比较规则
bool operator () (ListNode *a, ListNode *b) {
return a->val > b->val;
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
priority_queue<ListNode*, vector<ListNode*>, cmp> q;
for (int i = 0; i < lists.size(); ++i)
if (lists[i])
q.push(lists[i]);
ListNode *head = NULL, *pre = NULL, *tmp = NULL;
while (!q.empty()) {
tmp = q.top();
q.pop();
if (!pre) head = tmp;
else pre->next = tmp;
pre = tmp;
if (tmp->next) q.push(tmp->next);
}
return head;
}
};
leetcode#23 Merge k Sorted Lists
标签:pre com nal empty solution next describe val struct
原文地址:https://www.cnblogs.com/lsaejn/p/9723044.html