Skip to content

Commit f74d3b1

Browse files
committed
Runtime: 308 ms (Top 36.34%) | Memory: 71.4 MB (Top 24.44%)
1 parent a3c5c92 commit f74d3b1

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed
+18-17
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,28 @@
1+
// Runtime: 308 ms (Top 36.34%) | Memory: 71.4 MB (Top 24.44%)
12
function getListSize(head) {
23
let curr = head;
34
let size = 0;
4-
5+
56
while(curr !== null) {
67
size += 1;
7-
8+
89
curr = curr.next;
910
}
10-
11+
1112
return size;
1213
}
1314

1415
function splitInHalf(head, n) {
1516
let node1 = head;
1617
let curr = head;
17-
18+
1819
for (let i = 0; i < Math.floor(n / 2) - 1; i++) {
1920
curr = curr.next;
2021
}
21-
22+
2223
const node2 = curr.next;
2324
curr.next = null;
24-
25+
2526
return [
2627
node1,
2728
Math.floor(n / 2),
@@ -34,45 +35,45 @@ function merge(head1, head2) {
3435
if (head1.val > head2.val) {
3536
return merge(head2, head1)
3637
}
37-
38+
3839
const head = head1;
3940
let curr = head1;
40-
41+
4142
let runner1 = curr.next;
4243
let runner2 = head2;
43-
44+
4445
while (runner1 !== null || runner2 !== null) {
4546
const runner1Value = runner1 ? runner1.val : Infinity;
4647
const runner2Value = runner2 ? runner2.val : Infinity;
47-
48+
4849
if (runner1Value < runner2Value) {
4950
curr.next = runner1;
5051
runner1 = runner1.next;
5152
} else {
5253
curr.next = runner2;
5354
runner2 = runner2.next;
5455
}
55-
56+
5657
curr = curr.next;
5758
}
58-
59+
5960
curr.next = null;
6061
return head;
6162
}
6263

6364
var sortList = function(head) {
6465
const size = getListSize(head);
65-
66+
6667
function mergeSort(node, n) {
6768
if (n <= 1) {
6869
return node;
6970
}
70-
71+
7172
const [node1, n1, node2, n2] = splitInHalf(node, n);
7273
const [merged1, merged2] = [mergeSort(node1, n1), mergeSort(node2, n2)];
73-
74+
7475
return merge(merged1, merged2);
7576
}
76-
77+
7778
return mergeSort(head, size);
78-
};
79+
};

0 commit comments

Comments
 (0)