Skip to content

Commit 51cb0c7

Browse files
committed
top k frequent elements #1
1 parent 2beb39e commit 51cb0c7

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* 시간 복잡도: O(n log n)
3+
* - nums 배열 순회하며 빈도수 카운트: O(n)
4+
* - 빈도수 기준 내림차순 정렬: O(n log n)
5+
* - 상위 k개 선택: O(k) -> k는 n보다 작으므로 무시
6+
*
7+
* 공간 복잡도: O(n)
8+
* - countNums 객체: 최악의 경우 모든 숫자가 다른 경우 O(n)
9+
* - sortedCountNums 배열: countNums와 동일한 크기 O(n)
10+
* - answer 배열: k 크기이지만 k는 n보다 작으므로 무시
11+
*/
12+
const topKFrequent = (nums, k) => {
13+
// 각 숫자의 빈도수를 저장하는 객체
14+
const countNums = {};
15+
16+
// nums 배열을 순회하며 각 숫자의 빈도수를 카운트
17+
for (let i = 0; i < nums.length; i += 1) {
18+
const num = nums[i];
19+
countNums[num] = !countNums[num] ? 1 : countNums[num] + 1;
20+
}
21+
22+
// 빈도수를 기준으로 내림차순 정렬
23+
const sortedCountNums = Object.entries(countNums).sort((a, b) => b[1] - a[1]);
24+
const answer = [];
25+
26+
// 상위 k개의 숫자를 answer 배열에 저장
27+
for (let i = 0; i < k; i += 1) {
28+
answer[i] = Number(sortedCountNums[i][0]);
29+
}
30+
31+
return answer;
32+
};

0 commit comments

Comments
 (0)