Skip to content

Instantly share code, notes, and snippets.

@yangpeng-chn
Last active July 17, 2019 15:08
Show Gist options
  • Save yangpeng-chn/d03dd8980facadff1b49b8d8bc47eef6 to your computer and use it in GitHub Desktop.
Save yangpeng-chn/d03dd8980facadff1b49b8d8bc47eef6 to your computer and use it in GitHub Desktop.
K-way Merge
// min-heap
ListNode* mergeKLists(vector<ListNode*>& lists) {
auto comp = [](ListNode* a, ListNode* b) { return a->val > b->val; };
priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> pq(comp);
ListNode dummy(0);
ListNode *cur = &dummy;
for(ListNode *list : lists){
if(list) pq.push(list);
}
while(!pq.empty()){
cur->next = pq.top();
pq.pop();
cur = cur->next;
if(cur->next) //cur won't be nulltpr as cur is the element poped from the queue which is always non-nullptr, so we only need to check if its next is nullptr
pq.push(cur->next);
}
return dummy.next;
}
// devide and conquer
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){
ListNode dummy(0);
ListNode *cur = &dummy;
while(l1 && l2){
if(l1->val < l2->val){
cur->next = l1;
l1 = l1->next;
}else{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if(l1) cur->next = l1;
if(l2) cur->next = l2;
return dummy.next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n = lists.size();
while(n > 1){
int k = (n + 1) / 2;
for(int i = 0; i < n / 2; i++){
lists[i] = mergeTwoLists(lists[i], lists[i+k]);
}
n = k;
}
return lists.empty() ? nullptr : lists[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment