-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path347-Top-K-Frequent-Elements.cpp
More file actions
40 lines (33 loc) · 1.08 KB
/
347-Top-K-Frequent-Elements.cpp
File metadata and controls
40 lines (33 loc) · 1.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> umap;
vector<vector<int>> buckets(nums.size()+1); //Freq starts at 1 not 0
vector<int> ans;
for(auto num : nums){
umap[num]++;
}
for(auto i=umap.begin(); i!=umap.end(); i++){
buckets[i->second].push_back(i->first);
}
reverse(buckets.begin(), buckets.end());
for(auto bucket : buckets){
for(auto num : bucket){
ans.push_back(num);
if(ans.size() == k){
return ans;
}
}
}
return ans;
}
};
/* 347. Top-K-Frequent-Elements.cpp
//////////////////////////////////////////////////
Given an integer array nums and an integer k, return the k most frequent elements.
You may return the answer in any order.
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
https://leetcode.com/problems/top-k-frequent-elements/
//////////////////////////////////////////////////
*/