-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.js
More file actions
40 lines (32 loc) · 826 Bytes
/
Copy pathsolution.js
File metadata and controls
40 lines (32 loc) · 826 Bytes
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
/**
* @param {number[]} arr
* @return {number[][]}
*/
class Solution {
levelSort(arr) {
// Store the final answer
const ans = [];
// Current index in the array
let index = 0;
// Number of nodes at the current level
let levelSize = 1;
// Process every array element
while (index < arr.length) {
// Store one level
const level = [];
// Take at most levelSize elements
for (let i = 0; i < levelSize && index < arr.length; i++) {
level.push(arr[index]);
index++;
}
// Sort only the current level
level.sort((a, b) => a - b);
// Save it
ans.push(level);
// Next level has twice the nodes
levelSize *= 2;
}
// Return all sorted levels
return ans;
}
}