Skip to content

Commit b23ec77

Browse files
authored
[ PS ] : Top K Frequent Elements
1 parent bc47794 commit b23ec77

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
/**
2+
* 주어진 배열에서 가장 많이 속해있는 숫자 k개를 반환하는 함수
3+
* @param {number[]} nums
4+
* @param {number} k
5+
* @return {number[]}
6+
*/
7+
const topKFrequent = function(nums, k) {
8+
const count = {};
9+
nums.forEach((num) => {
10+
count[num] = count[num] + 1 || 1;
11+
});
12+
return Object.keys(count).sort((a, b) => count[b] - count[a]).slice(0, k).map(Number);
13+
};
14+
15+
// 시간복잡도: O(n)
16+
// 공간복잡도: O(n)

0 commit comments

Comments
 (0)