mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
35 lines
1.2 KiB
C++
35 lines
1.2 KiB
C++
class Solution{
|
|
public :
|
|
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){
|
|
if(!l1 || !l2) return l1?l1:l2;
|
|
if(l1->val < l2->val){
|
|
l1->next = mergeTwoLists(l1->next, l2);
|
|
return l1;
|
|
}else{
|
|
l2->next = mergeTwoLists(l1,l2->next);
|
|
return l2;
|
|
}
|
|
}
|
|
|
|
ListNode* mergeKLists(vector<ListNode*> &lists){
|
|
if(lists.empty()) return nullptr;
|
|
return divideAndConquer(lists, 0 , lists.size()-1);
|
|
}
|
|
ListNode* divideAndConquer(vector<ListNode*> &lists, int left, int right){
|
|
if(left == right) return lists[left];
|
|
|
|
int mid = left + (right-left)/2;
|
|
ListNode* l1 = divideAndConquer(lists, left, mid);
|
|
ListNode* l2 = divideAndConquer(lists, mid+1, right);
|
|
return mergeTwoLists(l1,l2);
|
|
}
|
|
};
|
|
|
|
//We recursively split the K lists into smaller groups, merge pairs of lists at the bottom, and keep merging upward until one sorted list remains.
|
|
|
|
//TC: O(nlogk) , Each level merges all nodes once, Number of levels = log₂(k), naive merging takes O(nk)
|
|
|
|
|
|
//SC : O(logK)
|
|
|