Skip to content

Commit b0fc4e3

Browse files
committed
solve: top-k-frequent-elements-1
1 parent 46057fc commit b0fc4e3

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+
* @description
3+
* time complexity: O(n log n)
4+
* space complexity: O(n)
5+
* runtime: 3ms
6+
* 풀이 방법:
7+
* ν•΄μ‹œλ§΅μ„ 톡해 각 숫자의 λΉˆλ„μˆ˜λ₯Ό 계산
8+
* ν•΄μ‹œλ§΅μ„ μ •λ ¬ν•˜μ—¬ λΉˆλ„μˆ˜κ°€ 높은 μˆœμ„œλŒ€λ‘œ μ •λ ¬
9+
* μ •λ ¬λœ 배열을 k만큼 μ§€λΌμ„œ λ°˜ν™˜
10+
* @param {number[]} nums
11+
* @param {number} k
12+
* @return {number[]}
13+
*/
14+
const topKFrequent = function (nums, k) {
15+
const hashMap = new Map();
16+
17+
for (const num of nums) {
18+
if (hashMap.has(num)) {
19+
hashMap.set(num, hashMap.get(num) + 1);
20+
} else {
21+
hashMap.set(num, 1);
22+
}
23+
}
24+
25+
return Array.from(hashMap.entries())
26+
.sort((a, b) => b[1] - a[1])
27+
.slice(0, k)
28+
.map(([num]) => num);
29+
};

0 commit comments

Comments
Β (0)