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
| class Solution { public: unordered_map<int,int> st; vector<pair<int,int>> a; vector<int> topKFrequent(vector<int>& nums, int k) { int n = nums.size(); vector<int> res; for(int i=0;i<n;i++){ st[nums[i]] ++; } auto it = st.begin(); while(it != st.end()) { a.push_back({it->second,it->first}); it ++; } sort(a.begin(),a.end()); for(int i = a.size()-1;i>=0;i--){ if(k == 0) break; res.push_back(a[i].second); k--; } return res; } };
|