Skip to content

Commit da7faf2

Browse files
committed
🚀 18-Jul-2020
1 parent 5a99823 commit da7faf2

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
Given a non-empty array of integers, return the k most frequent elements.
2+
3+
Example 1:
4+
5+
Input: nums = [1,1,1,2,2,3], k = 2
6+
Output: [1,2]
7+
Example 2:
8+
9+
Input: nums = [1], k = 1
10+
Output: [1]
11+
Note:
12+
13+
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
14+
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
15+
It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique.
16+
You can return the answer in any order.
17+
18+
19+
20+
21+
22+
23+
24+
25+
26+
class Solution {
27+
public:
28+
vector<int> topKFrequent(vector<int>& nums, int k) {
29+
vector<int>res;
30+
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; // min heap
31+
unordered_map<int, int> m;
32+
int n=nums.size();
33+
for(int i=0;i<n;i++){
34+
if(m.find(nums[i])!=m.end())
35+
m[nums[i]]++;
36+
else m.insert({nums[i], 1});
37+
}
38+
for(auto it=m.begin(); it!=m.end(); it++){
39+
pq.push({it->second, it->first});
40+
if(pq.size()>k) pq.pop();
41+
}
42+
43+
while(!pq.empty()){
44+
res.push_back(pq.top().second);
45+
pq.pop();
46+
}
47+
reverse(res.begin(), res.end());
48+
return res;
49+
}
50+
};

0 commit comments

Comments
 (0)