021.Merge Two Sorted Lists

Test case

1
2
3
4
[][]
[1][]
[][1]
[-1,0,5][1,2,3]

Solution 1: accepted

Well…this is a 2ms solution, but only beats 2%! We have to do more!

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
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode temp = result;
while (l1 != null || l2 != null) {
if (l1 == null) {
temp.next = new ListNode(l2.val);
l2 = l2.next == null? null : l2.next;
} else if (l2 == null) {
temp.next = new ListNode(l1.val);
l1 = l1.next == null? null : l1.next;
} else if (l1.val >= l2.val) {
temp.next = new ListNode(l2.val);
l2 = l2.next == null? null : l2.next;
} else if (l1.val < l2.val) {
temp.next = new ListNode(l1.val);
l1 = l1.next == null? null : l1.next;
}
temp = temp.next;
}
return result.next;
}
}

Solution 2: accepted

We only need to concatenate what’s left to the final result. This will significantly improve the performance when one list is much longer than the other.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode temp = result;
while (l1 != null && l2 != null) {
if (l1.val >= l2.val) {
temp.next = new ListNode(l2.val);
l2 = l2.next == null? null : l2.next;
} else if (l1.val < l2.val) {
temp.next = new ListNode(l1.val);
l1 = l1.next == null? null : l1.next;
}
temp = temp.next;
}
if (l1 != null)
temp.next = l1;
else if (l2 != null)
temp.next = l2;
return result.next;
}
}