Skip to content

Commit ba7602e

Browse files
committed
add: Top K Frequent Elements solution
1 parent 6f8cc1a commit ba7602e

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* [Idea]
3+
* 숫자와 등장 횟수를 세는 counter Map을 활용했다.
4+
* 1. counter Map을 만든 뒤
5+
* 2. 배열로 변환
6+
* 3. count 내림차순으로 정렬
7+
* 4. 정답 배열 만들기
8+
*
9+
* [Time Complexity]
10+
* O(n + m log m) => O(n log n) (n: nums의 길이, m: nums에서 unique elements의 개수)
11+
* - counter Map을 생성할 때 O(n)
12+
* - counter를 배열로 변환해서 정렬할 때 O(m log m)
13+
* - sortedCounter를 k 길이로 자르고 count만 담은 배열로 만들 때 O(k)
14+
*
15+
* [Space Complexity]
16+
* O(m + k) => O(n)
17+
* - counter Map의 O(m)
18+
* - 정답 배열을 만들 때 추가로 사용하는 O(k)
19+
*/
20+
function topKFrequent1(nums: number[], k: number): number[] {
21+
const counter = new Map<number, number>(); // key: 숫자, value: count
22+
for (const num of nums) {
23+
const count = counter.get(num);
24+
counter.set(num, count === undefined ? 1 : count + 1);
25+
}
26+
27+
const sortedCounter = [...counter].sort((a, b) => b[1] - a[1]);
28+
return sortedCounter.slice(0, k).map((count) => count[0]);
29+
}

0 commit comments

Comments
 (0)