码迷,mamicode.com
首页 > 其他好文 > 详细

347. Top K Frequent Elements

时间:2020-02-06 14:26:57      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:air   sum   input   note   ber   back   for   always   tput   

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;
    }
};

 

347. Top K Frequent Elements

标签:air   sum   input   note   ber   back   for   always   tput   

原文地址:https://www.cnblogs.com/qiang-wei/p/12268357.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!