Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
bool operator <(const pair<ListNode*,int> &p1, const pair<ListNode*,int> &p2){
return p1.first->val < p2.first->val;
}
/*假设投针数组为副本,且由其它地方销毁*/
#include<queue>
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* helpNode = new ListNode(0);
ListNode* cur = helpNode;
typedef pair<ListNode*,int> heaptype;
priority_queue<heaptype,vector<heaptype>,greater<heaptype>> q;//最小队列
for(int i = 0; i< lists.size(); ++i){
if(lists[i]){
q.push(make_pair(lists[i],i));
lists[i] = lists[i]->next;
}
}
while(!q.empty()){
ListNode* node = q.top().first;
int index = q.top().second;
q.pop();
if(lists[index]){
q.push(make_pair(lists[index],index));
lists[index] = lists[index]->next;
}
cur->next = new ListNode(node->val);
cur= cur->next;
}
auto ret = helpNode->next;
delete helpNode;
return ret;
}
};