Skip to content

Commit 75e1768

Browse files
committed
week1: top-k-frequent-elements
1 parent 59a5cfb commit 75e1768

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const topKFrequent = (nums, k) => {
2+
// 1: ๋“ฑ์žฅ ํšŸ์ˆ˜ ์„ธ๊ธฐ
3+
const countMap = new Map();
4+
for (const num of nums) {
5+
countMap.set(num, (countMap.get(num) ?? 0) + 1);
6+
}
7+
8+
// 2: ๋ฒ„ํ‚ท ๋ฐฐ์—ด ๋งŒ๋“ค๊ธฐ
9+
// ์ธ๋ฑ์Šค = ๋นˆ๋„์ˆ˜, ๊ฐ’ = ๊ทธ ๋นˆ๋„์ˆ˜๋ฅผ ๊ฐ€์ง„ ์ˆซ์ž๋“ค์˜ ๋ฐฐ์—ด
10+
// ์ตœ๋Œ€ ๋นˆ๋„๋Š” nums.length์ด๋ฏ€๋กœ ํฌ๊ธฐ๋ฅผ nums.length + 1๋กœ ์„ค์ •
11+
const bucket = Array.from({ length: nums.length + 1 }, () => []);
12+
13+
for (const [num, freq] of countMap.entries()) {
14+
bucket[freq].push(num);
15+
}
16+
17+
// 3: ๋’ค(๋†’์€ ๋นˆ๋„)์—์„œ๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•˜๋ฉฐ k๊ฐœ ์ˆ˜์ง‘
18+
const result = [];
19+
for (let i = bucket.length - 1; i >= 0 && result.length < k; i--) {
20+
for (const num of bucket[i]) {
21+
result.push(num);
22+
if (result.length === k) break;
23+
}
24+
}
25+
26+
return result;
27+
}

0 commit comments

Comments
ย (0)