题目
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例1
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
实例2
输入: nums = [1], k = 1
输出: [1]
思路一
- 可以通过nums构造一个pair对数组。一个pair对包括<元素频数,元素值>。通过元素频数进行排序,取最高的k个数。排序的效率为 O(nlogn)。如果用快排的partition方法,每次值操作一半的区间,可以得到O(n)的复杂度(待证明)。
思路二
- 先用哈希表,计算每个数的频率。然后构造一个桶,按照频数把元素放到对应的桶里面,然后遍历这个桶,取前k高频率的元素。
代码二
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
if ( nums.size() < k || k == 0 ) return {};
unordered_map<int,int> ht;
vector<vector<int>> buckets( nums.size() + 1 );
vector<int> res( k );
for ( auto& n : nums )
++ht[n];
for ( auto& it : ht )
buckets[it.second].push_back( it.first );
int index = 0;
for ( int i = nums.size(); i >= 0 && index != k; --i ) {
if ( buckets[i].size() == 0 ) continue;
for ( int j = 0; j < buckets[i].size() && index != k; ++j )
res[index++] = buckets[i][j];
}
return res;
}
};