Leetcode 23. Merge k Sorted Lists (Hard) (cpp)
Tag: Divide and Conquer, Linked List, Heap
Difficulty: Hard
/*
23. Merge k Sorted Lists (Hard)
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) {}
* };
*/
class Comp {
public:
bool operator()(pair<ListNode*, int> p1, pair<ListNode*, int> p2) {
return p1.first->val > p2.first->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<pair<ListNode*, int>, vector<pair<ListNode*, int>>, Comp> pq;
ListNode *dummy = new ListNode(-1);
ListNode *cur = dummy;
for (int i = 0; i < lists.size();i++) {
if (lists[i] != NULL) {
pq.push(make_pair(lists[i], i));
}
}
while (!pq.empty()) {
pair<ListNode*, int> p = pq.top();
pq.pop();
cur->next = p.first;
cur = cur->next;
lists[p.second] = lists[p.second]->next;
if (lists[p.second] != NULL) {
pq.push(make_pair(lists[p.second], p.second));
}
}
return dummy->next;
}
};