347. Top K Frequent Elements

Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

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.
方案1:桶排序
class Solution {
public:
    // 桶排序
    vector<int> topKFrequent(vector<int>& nums, int k) {
        vector<vector<int>>bucket(nums.size() + 1);
        unordered_map<int, int> fre;
        for (auto num: nums)
        {
            if(fre.find(num) == fre.end())
            {
                fre[num] = 1;
            }
            else
            {
                fre[num] = fre[num] + 1;
            }
        }
        
        for (auto f: fre)
        {
            bucket[f.second].push_back(f.first);
        }
        vector<int> res;
        for (int i = bucket.size() - 1; i >= 0 ; --i)
        {
            if (!bucket[i].empty())
                for (auto b : bucket[i]) {
                    res.push_back(b);
                    if (res.size() == k)return res;
                }
        }
        return res;
    }
};

 

方案二:利用优先队列

class Solution {
public:
    // 桶排序
    vector<int> topKFrequent(vector<int>& nums, int k) {
        unordered_map<int, int> fre;
        for (auto num: nums)
        {
            fre[num]++;
        }
        vector<int> res;
        // 优先队列
        priority_queue<pair<int, int>> pq;
        for (auto f: fre)
        {
            pq.push(make_pair(f.second,f.first));
            if (pq.size() > fre.size() - k)
            {
                res.push_back(pq.top().second);
                pq.pop();
            }
        }
        return res;
    }
};

 

posted @ 2020-02-06 13:15  强威  阅读(113)  评论(0编辑  收藏  举报