Skip to content

Commit 0057ff1

Browse files
committed
top-k-frequent-elements solution
1 parent 475cc7c commit 0057ff1

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
vector<int> topKFrequent(vector<int>& nums, int k) {
4+
unordered_map<int, int> count;
5+
6+
// 1. nums์˜ ๊ฐ ์›์†Œ count
7+
for (int num : nums) {
8+
count[num]++; // count์— num์— ํ•ด๋‹นํ•˜๋Š” value์—๋Š” 1์ฆ๊ฐ€
9+
}
10+
11+
// 2. ๋งŽ์ด ๋‚˜์˜จ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌ
12+
vector<pair<int, int>> freqs(count.begin(), count.end());
13+
sort(freqs.begin(), freqs.end(), [](pair<int, int> a, pair<int, int> b) {
14+
return a.second > b.second;
15+
});
16+
17+
// 3. ์ƒ์œ„ k๊ฐœ ์ถ”์ถœ
18+
vector<int> max(k);
19+
for (int i = 0; i < k; i++) {
20+
max[i] = freqs[i].first;
21+
}
22+
23+
return max;
24+
}
25+
};
26+

0 commit comments

Comments
ย (0)