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)