Skip to content

Commit 635b515

Browse files
한윤석한윤석
authored andcommitted
top k frequent elemetns solution
1 parent 79f2ab4 commit 635b515

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <bits/stdc++.h>
2+
3+
class Solution {
4+
public:
5+
vector<int> topKFrequent(vector<int>& nums, int k) {
6+
map<int, int> count;
7+
8+
for(int i = 0; i < nums.size(); i++) {
9+
if(count.find(nums[i]) == count.end())
10+
count[nums[i]] = 1;
11+
else
12+
count[nums[i]]++;
13+
}
14+
15+
vector<pair<int, int>> cnt(count.begin(), count.end());
16+
sort(cnt.begin(), cnt.end(), cmp);
17+
18+
vector<int> ans;
19+
for(int i = 0; i < k; i++)
20+
ans.push_back(cnt[i].first);
21+
22+
return ans;
23+
}
24+
25+
static bool cmp(const pair<int, int>& a, const pair<int, int>& b) {
26+
return a.second > b.second;
27+
}
28+
};

0 commit comments

Comments
 (0)