Created
January 14, 2025 09:51
-
-
Save JodhwaniMadhur/ba32843abd7b932b705736956fbcbe93 to your computer and use it in GitHub Desktop.
Merge K Sorted Lists | C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for singly-linked list. | |
* struct ListNode { | |
* int val; | |
* ListNode *next; | |
* ListNode() : val(0), next(nullptr) {} | |
* ListNode(int x) : val(x), next(nullptr) {} | |
* ListNode(int x, ListNode *next) : val(x), next(next) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
ListNode* mergeKLists(vector<ListNode*>& lists) { | |
//TC - O(N log K) | |
//SC - O(K) | |
if (lists.empty()) return NULL; | |
priority_queue<pair<int, ListNode*>> pq; | |
for(auto ll:lists) | |
{ | |
if(ll != NULL) | |
{ | |
pair<int, ListNode*> p; | |
p.first = -ll->val; | |
p.second = ll; | |
pq.push(p); | |
} | |
} | |
ListNode* dummyRoot = new ListNode(INT_MAX); | |
ListNode* end = dummyRoot; | |
while(!pq.empty()) | |
{ | |
pair<int, ListNode*> poppedList = pq.top(); | |
pq.pop(); | |
end->next = poppedList.second; | |
end = end->next; | |
if(end->next != NULL) | |
{ | |
poppedList.first = -end->next->val; | |
poppedList.second = end->next; | |
pq.push(poppedList); | |
} | |
} | |
return dummyRoot->next; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment