-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0021. Merge Two Sorted Lists.js
107 lines (100 loc) · 2.15 KB
/
0021. Merge Two Sorted Lists.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
// Example:
// Input: 1->2->4, 1->3->4
// Output: 1->1->2->3->4->4
// 1)
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const mergeTwoLists = (l1, l2) => {
if (!l1) {
return l2
} else if (!l2) {
return l1
}
let l = new ListNode(0)
let cur = l
while (l1 && l2) {
if (l1.val < l2.val) {
let node = new ListNode(l1.val)
cur.next = node
l1 = l1.next
} else {
let node = new ListNode(l2.val)
cur.next = node
l2 = l2.next
}
cur = cur.next
}
if (l1) {
cur.next = l1
} else {
cur.next = l2
}
return l.next
}
// Runtime: 72 ms, faster than 26.08% of JavaScript online submissions for Merge Two Sorted Lists.
// Memory Usage: 35.5 MB, less than 89.74% of JavaScript online submissions for Merge Two Sorted Lists.
// 2) 递归
// 注意在递归调用过程中,声明了多个 l,最终在出栈过程中返回了第一个 l
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const mergeTwoLists = (l1, l2) => {
if (!l1) {
return l2
} else if (!l2) {
return l1
}
let l
if (l1.val < l2.val) {
l = l1
l.next = mergeTwoLists(l1.next, l2)
} else {
l = l2
l.next = mergeTwoLists(l1, l2.next)
}
return l
}
// Runtime: 76 ms, faster than 16.64% of JavaScript online submissions for Merge Two Sorted Lists.
// Memory Usage: 35.5 MB, less than 89.74% of JavaScript online submissions for Merge Two Sorted Lists.
// Test case:
// let l1 = {
// val: 1,
// next: {
// val: 2,
// next: {
// val: 3,
// next: null
// }
// }
// }
// let l2 = {
// val: 1,
// next: {
// val: 2,
// next: {
// val: 4,
// next: null
// }
// }
// }
// console.log(mergeTwoLists(l1, l2));