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;
        }
    };
  • 相关阅读:
    百度Hi之CSRF蠕虫攻击
    Portlet之讲解
    try-catch语句讲解
    unset之讲解
    MySQL bin-log 日志清理方式
    php数组array_push()和array_pop()以及array_shift()函数
    php中的func_num_args、func_get_arg与func_get_args函数
    PHP is_callable 方法
    如何实现php异步处理
    Mysql并发时经典常见的死锁原因及解决方法
  • 原文地址:https://www.cnblogs.com/qiang-wei/p/12268357.html
Copyright © 2011-2022 走看看