Skip to content

Commit 856ebed

Browse files
committed
✨ [374] Bucket sort
1 parent f01b771 commit 856ebed

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed

374/my_solution.js

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
2+
/**
3+
* @param {number[]} nums
4+
* @param {number} k
5+
* @return {number[]}
6+
*/
7+
const topKFrequent = (nums, k) => {
8+
// [1,1,1,2,2,3]
9+
if (k < 1) return [];
10+
11+
// a map of the appear nb, a list of nums length to store the list based on appr nb
12+
let map = new Map(), kList = Array.from({ length: nums.length + 1}, () => []);
13+
// Array(nums.length).fill([]); - This will fill the array with empty arrays but it has the same references to each item (array).
14+
// you are actually pushing values into the same array instance across all indices.
15+
16+
17+
// process the map
18+
for (let i = 0; i < nums.length; i++) {
19+
map.set(nums[i], (map.get(nums[i]) || 0) + 1)
20+
}
21+
22+
// i will have a k list then to get from behind, (pop) if empty, nth, otherwise, K--; ⇒ 0
23+
// [[], …]
24+
console.log(map)
25+
console.log(kList)
26+
for (let [key, value] of map) {
27+
console.log(value)
28+
console.log(kList[value])
29+
kList[value].push(key);
30+
console.log("kList")
31+
console.log(kList)
32+
}
33+
34+
// [[],[3],[2],[1], …]
35+
let result = [], tmpK = k;
36+
37+
while (tmpK > 0) {
38+
let curr = kList.pop();
39+
if (0 < curr.length) {
40+
result.push(curr);
41+
tmpK -= curr.length;
42+
}
43+
}
44+
// [[1,2], [3]]
45+
46+
47+
console.log("result")
48+
console.log(k)
49+
console.log(result.flat())
50+
console.log(result.flat().slice(0, k))
51+
52+
return result.flat().slice(0, k);
53+
}
54+
// topKFrequent([1, 1, 1, 2, 2, 2, 3], 2)
55+
// topKFrequent([1], 1)
56+
// topKFrequent([1,2], 2)

374/solution.js

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
2+
/**
3+
* @param {number[]} nums
4+
* @param {number} k
5+
* @return {number[]}
6+
*/
7+
const topKFrequent = (nums, k) => {
8+
if (k < 1) return [];
9+
10+
let map = new Map(), kList = Array.from({ length: nums.length + 1 }, () => []);
11+
12+
for (let i = 0; i < nums.length; i++) {
13+
map.set(nums[i], (map.get(nums[i]) || 0) + 1)
14+
}
15+
16+
for (let [key, value] of map) {
17+
kList[value].push(key);
18+
}
19+
20+
let result = [], tmpK = k;
21+
while (tmpK > 0) {
22+
let curr = kList.pop();
23+
if (0 < curr.length) {
24+
result.push(curr);
25+
tmpK -= curr.length;
26+
}
27+
}
28+
29+
return result.flat().slice(0, k);
30+
}

0 commit comments

Comments
 (0)