合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入: [ 1->4->5, 1->3->4, 2->6 ] 输出: 1->1->2->3->4->4->5->6
自己用set实现的。嗯,实现方式不优雅,会导致性能下降,应该直接用set存储ListNode*然后手写比较函数的,那样子和标称就一样了。
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* root = new ListNode(0);
vector<int> idx;
set< int > s;
for (int i = 0; i < lists.size(); ++i) {
idx.emplace_back(0);
if (lists[i] != NULL) {
s.insert(lists[i]->val);
}
}
ListNode* p = root;
while (!s.empty()) {
int tgt = *(s.begin());
for (int i = 0; i < lists.size(); ++i) {
while (lists[i] != NULL && lists[i]->val == tgt) {
ListNode* tmp = new ListNode(tgt);
p->next = tmp;
p = tmp;
lists[i] = lists[i]->next;
if (lists[i] != NULL && lists[i]->val != tgt) {
s.insert(lists[i]->val);
}
}
}
s.erase(tgt);
}
return root->next;
}
};
标准代码用优先队列实现的。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
class priority{
public:
bool operator () (ListNode* a, ListNode* b){
if(a == NULL)
return false;
else if(b == NULL)
return true;
else
return a->val>b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty())
return NULL;
priority_queue<ListNode*, vector<ListNode*>, priority> help;
ListNode* ret_val = new ListNode(0);
auto temp_node = ret_val;
for(auto i:lists)
help.push(i);
while(!help.empty()){
auto temp = help.top();
help.pop();
if(temp != NULL){
temp_node->next = temp;
temp_node = temp_node->next;
help.push(temp->next);
}
}
return ret_val->next;
}
};