347. Top K Frequent Elements

问题描述:

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 [1,2].

Note: 

  • You may assume k is 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.

解题思路:

首先遍历一边数组统计每个数字出现的频率并将(num, freq)存入hash表中

然后创建一个频率的数组来存储该频率的数字:vector<vector<int>> freq(nums.size()+1)

大小为nums.size()+1的原因为存在整个数组只有一个数字的可能性。

从尾部向前检索,到k为0时,跳出循环。

需要注意的是k--应当放在最内层循环。

代码:

class Solution {
public:
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> m;
        vector<int> ret;
        for(int n:nums){
            m[n]++;
        }
        vector<vector<int>> freq(nums.size()+1);
        for(auto p : m){
            freq[p.second].push_back(p.first);
        }
        for(int i = nums.size(); i > -1;i--){
            if(freq[i].empty()){
                continue;
            }
            for(int j = 0; j < freq[i].size(); j++){
                ret.push_back(freq[i][j]);
                k--;
            }
            if(k == 0)
                break;
        }
        
        return ret;
    }
};

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9175842.html