Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 90b6bce

Browse files
committedApr 1, 2025
add solution : 347. Top K Frequent Elements
1 parent 9e763c1 commit 90b6bce

File tree

2 files changed

+38
-33
lines changed

2 files changed

+38
-33
lines changed
 

โ€Žtop-k-frequent-elements/mmyeon.js

Lines changed: 0 additions & 33 deletions
This file was deleted.

โ€Žtop-k-frequent-elements/mmyeon.ts

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
*
3+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
4+
* - ์ •๋ ฌ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  o(n)์„ ํ’€๊ธฐ ์œ„ํ•ด์„œ ์ˆซ์ž ๋นˆ๋„์ˆ˜๋ฅผ ๋ฐฐ์—ด ์ธ๋ฑ์Šค๋กœ ์ €์žฅ
5+
* - ์ˆซ์ž ๋นˆ๋„์Šค๋ฅผ ๋งต์— ์ €์žฅ
6+
* - ๋งต์„ ์ˆœํšŒํ•˜๋ฉด์„œ, ๋นˆ๋„์ˆ˜๋ฅผ ๋ฐฐ์—ด์— ์ €์žฅ (๋™์ผ ๋ฐ˜๋„์ˆ˜ ์ฒ˜๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด์„œ 2์ฐจ์› ๋ฐฐ์—ด ์‚ฌ์šฉ)
7+
* - ๋ฐฐ์—ด์„ ์—ญ์ˆœ์œผ๋กœ ์ˆœํšŒํ•˜๋ฉด์„œ ๋นˆ๋„์ˆ˜ ๊ธฐ๋ฐ˜์˜ ๊ฐ’์„ ๊ฒฐ๊ณผ ๋ฐฐ์—ด์— ์ €์žฅ
8+
* - ๊ฒฐ๊ณผ ๋ฐฐ์—ด์„ k๊ฐœ๋งŒํผ ์ž˜๋ผ์„œ ๋ฆฌํ„ด
9+
*
10+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(n)
11+
* - nums ๋ฐฐ์—ด 1ํšŒ ์ˆœํšŒํ•˜๋ฉด์„œ ๋งต์— ์ €์žฅํ•˜๋‹ˆ๊นŒ O(n)
12+
*
13+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(n)
14+
* - nums ๋ฐฐ์—ด ๊ธธ์ด๋งŒํผ ๋งต๊ณผ 2์ฐจ์› ๋ฐฐ์—ด์— ์ •๋ฆฌํ•˜๋‹ˆ๊นŒ O(n)
15+
*/
16+
function topKFrequent(nums: number[], k: number): number[] {
17+
const numMap = new Map();
18+
19+
for (const num of nums) {
20+
numMap.set(num, (numMap.get(num) ?? 0) + 1);
21+
}
22+
23+
const storedArr: number[][] = Array(nums.length + 1)
24+
.fill(null)
25+
.map(() => []);
26+
27+
for (const [num, frequency] of numMap) {
28+
storedArr[frequency].push(num);
29+
}
30+
31+
const result: number[] = [];
32+
33+
for (let i = storedArr.length - 1; i >= 0; i--) {
34+
if (storedArr[i].length > 0) result.push(...storedArr[i]);
35+
}
36+
37+
return result.slice(0, k);
38+
}

0 commit comments

Comments
 (0)
Please sign in to comment.