Skip to content

Instantly share code, notes, and snippets.

@bunnyadad
Last active May 15, 2019 02:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bunnyadad/509d5049fe6f6d2f063931e981c9c7ec to your computer and use it in GitHub Desktop.
Save bunnyadad/509d5049fe6f6d2f063931e981c9c7ec to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists)
{
if (lists.size()==0) return nullptr;
size_t delta = 1;
while (delta < lists.size())
{
for (int i=0; i<lists.size()-delta; i=i+2*delta)
lists[i] = mergeTwoLists(lists[i], lists[i+delta]);
delta *= 2;
}
return lists[0];
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
auto v1 = l1->val;
auto v2 = l2->val;
auto root = v1 <= v2 ? l1 : l2;
v1 <= v2 ? (l1 = l1->next) : (l2 = l2->next);
auto cur = root;
while (l1 != NULL && l2 != NULL)
{
if (l1->val <= l2->val)
{
cur->next = l1;
l1 = l1->next;
}
else
{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 != NULL ? l1 : l2;
return root;
}
};
@bunnyadad
Copy link
Author

Runtime: 80 ms, faster than 31.01% of C++ online submissions for Merge k Sorted Lists.
Memory Usage: 10.9 MB, less than 90.17% of C++ online submissions for Merge k Sorted Lists.

@bunnyadad
Copy link
Author

Runtime: 28 ms, faster than 90.64% of C++ online submissions for Merge k Sorted Lists.
Memory Usage: 11.8 MB, less than 43.30% of C++ online submissions for Merge k Sorted Lists.

@bunnyadad
Copy link
Author

Runtime: 24 ms, faster than 99.23% of C++ online submissions for Merge k Sorted Lists.
Memory Usage: 10.8 MB, less than 93.34% of C++ online submissions for Merge k Sorted Lists.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment