Given a non-empty array of integers, return the K most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [+].
Note:
You may assume k are always valid, 1≤k≤number of unique elements.
Your algorithm's time complexity must be better than O (n log n), where n is the array ' s size.
This problem gives us an array, let us count the first k high-frequency numbers, then for this kind of statistics problem, first of all, we should consider using a hash table to do, establish the number and its number of occurrences of the map, and then by the number of occurrences to sort. We can do it with a heap sort, using a maximum heap to order the number of mappings from large to small, using priority_queue in C + +, the default is the maximum heap, see code as follows:
Solution One:
classSolution { Public: Vector<int> Topkfrequent (vector<int>& Nums,intk) {unordered_map<int,int>m; Priority_queue<pair<int,int>>Q; Vector<int>Res; for(auto a:nums) + +M[a]; for(Auto it:m) Q.push ({it.second, it.first}); for(inti =0; I < K; ++i) {res.push_back (Q.top (). second); Q.pop (); } returnRes; }};
We can also use the bucket sort, after establishing the number and its number of occurrences of the map, we put the number in the corresponding position according to the number of occurrences, so we go from the back of the bucket to the front, the first to get the number of occurrences of the most number, we find K after the return, see the code is as follows:
Solution Two:
classSolution { Public: Vector<int> Topkfrequent (vector<int>& Nums,intk) {unordered_map<int,int>m; Vector<vector<int>> Buckets (nums.size () +1); Vector<int>Res; for(auto a:nums) + +M[a]; for(Auto it:m) {bucket[it.second].push_back (It.first); } for(inti = Nums.size (); I >=0; --i) { for(intj =0; J < Bucket[i].size (); ++j) {Res.push_back (bucket[i][j]); if(res.size () = = k)returnRes; } } returnRes; }};
Similar topics:
Kth largest Element in an Array
Word Frequency
Resources:
Https://leetcode.com/discuss/100636/c-o-nlogk-and-o-n-solutions
Https://leetcode.com/discuss/100713/3-ways-to-solve-this-problem
Leetcode all in one topic summary (continuous update ...)
[Leetcode] Top K frequent Elements top K high Frequency elements