题目描述
合并\ k k 个已排序的链表并将其作为一个已排序的链表返回。分析并描述其复杂度。
示例1
输入
复制
[{1,2,3},{4,5,6,7}]
返回值
复制
{1,2,3,4,5,6,7}
说明:本题目包含复杂数据结构ListNode,点此查看相关信息
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
ListNode fake(0);
ListNode *cur = &fake;
vector<ListNode *> vec;
int n = lists.size();
for (int i=0;i< n;++i) {
if (lists[i]) vec.push_back(lists[i]);
}
make_heap(vec.begin(), vec.end(),cmp);
while (vec.size()) {
cur -> next = vec.front();
pop_heap(vec.begin(),vec.end(),cmp); // 将first 和 n-1 进行交换
vec.pop_back();
cur = cur -> next;
if (cur -> next) {
vec.push_back(cur->next);
push_heap(vec.begin(),vec.end(),cmp);
}
}
return fake.next;
}
static bool cmp(ListNode* l1, ListNode* l2) {
return l1-> val > l2->val;
}
};