Skip to content

Commit 63f4483

Browse files
committed
top k frequent elements solution
1 parent 8937108 commit 63f4483

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number[]}
5+
*/
6+
7+
function topKFrequent(nums, k) {
8+
// ์ˆซ์ž์˜ ๋นˆ๋„๋ฅผ ์ €์žฅํ•  Map ์ƒ์„ฑ
9+
const frequency = new Map();
10+
11+
// ๋นˆ๋„ ๊ณ„์‚ฐ
12+
for (const num of nums) {
13+
// Map์— ์ด๋ฏธ ์ˆซ์ž๊ฐ€ ์žˆ์œผ๋ฉด +1, ์—†์œผ๋ฉด 1๋กœ reset
14+
frequency.set(num, (frequency.get(num) || 0) + 1);
15+
}
16+
17+
// ๋นˆ๋„ ์ˆœ์œผ๋กœ ์ˆซ์ž ์ •๋ ฌ ํ›„ ๊ฐ€์žฅ ๋นˆ๋„๊ฐ€ ๋†’์€ k๊ฐœ์˜ ์ˆซ์ž๋ฅผ ๋ฐ˜ํ™˜
18+
return [...frequency.entries()] // entries๋ฅผ ์ด์šฉํ•ด Map์„ ๋ฐฐ์—ด๋กœ ๋ณ€ํ™˜
19+
.sort((a, b) => b[1] - a[1])
20+
.slice(0, k)
21+
.map(entry => entry[0]);
22+
}

0 commit comments

Comments
ย (0)