23. Merge k Sorted Lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { multimap<int, ListNode*> m; ListNode* dummy = new ListNode(); for(auto n : lists) { if(n) m.insert({n->val, n}); } ListNode* cur = dummy; while(m.size() > 1) { auto rm = m.begin(); cur->next = rm->second; if(rm->second->next) { m.insert({rm->second->next->val, rm->second->next}); } m.erase(rm); cur = cur->next; } cur->next = m.begin()->second; return dummy->next; } };
|