zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    docker---基本操作
    one_day_one_linuxCmd---netstat命令
    docker---Dockerfile编写
    one_day_one_linuxCmd---sz命令
    one_day_one_linuxCmd---scp命令
    同义英语词汇整理
    网络实习——校园网络设计方案
    实现 FTP 客户端和服务器程序所调用的系统函数
    2020年上半年总结
    单片机的串行总线拓展技术
  • 原文地址:https://www.cnblogs.com/qiang-wei/p/12268357.html
Copyright © 2011-2022 走看看