Skip to content

Instantly share code, notes, and snippets.

@bunnyadad
Last active May 3, 2019 03:44
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/4ec81c8eaa5690025324a35f5a38ee88 to your computer and use it in GitHub Desktop.
Save bunnyadad/4ec81c8eaa5690025324a35f5a38ee88 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* 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: 8 ms, faster than 100.00% of C++ online submissions for Merge Two Sorted Lists.
Memory Usage: 9 MB, less than 99.71% of C++ online submissions for Merge Two Sorted Lists.

@bunnyadad
Copy link
Author

Runtime: 8 ms, faster than 100.00% of C++ online submissions for Merge Two Sorted Lists.
Memory Usage: 8.8 MB, less than 100.00% of C++ online submissions for Merge Two Sorted Lists.

  • Why?
    auto root = l1->val<= l1->val? l1 : l2;
    l1->val<= l1->val? (l1 = l1->next) : (l2 = l2->next);
    Speed change to 16ms

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