Last active
May 3, 2019 03:44
-
-
Save bunnyadad/4ec81c8eaa5690025324a35f5a38ee88 to your computer and use it in GitHub Desktop.
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(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; | |
} | |
}; |
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
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.