zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】查找与排序题12:Top K Frequent Elements

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    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.

    C++
     
    //问题:返回数组中出现频次前k大的元素
    using namespace std;
    #include <algorithm>
    #include <unordered_map>
    class Solution
    {
    public:
        vector<int> topKFrequent(vector<int>& a, int k)
        {
            unordered_map<int,int> counter; //出现频次计数器map 
            priority_queue<pair<int, int>> q; //注意<pair<int, int>>的用法
            vector<int> res; //用于存储结果
           
            for(auto key:a) counter[key]++; //用counter[key]访问map中为key的value,按<数字,频次> 组织map
            for(auto it:counter) q.push({it.second, it.first}); //注意使用{}对,按<频次,数字> 组织,构建一个大顶堆(默认)
            for(int i=0;i<k; i++)//输出前k个最大值
            {
                res.push_back(q.top().second);
                q.pop();
            }
            return res;
           
            //时间分析:
            //构建map耗时O(n),构建大顶堆O(nlogn),输出前k个数O(klogn),时间复杂度O(nlogn)
        }
    };
    /*无法做出
    //计数得统计“直方图”,再用堆排序找前k个元素
    #include <algorithm>
    class Solution
    {
    public:
        vector<int> topKFrequent(vector<int>& a, int k)
        {
            vector<int> count(k); //出现频次计数器
            for(int i=0; i < a.size(); i++) //频次计数,一次遍历,时间复杂度为O(n)
            {
                count[a[i]]++;
            }
           
            partial_sort(count.begin(), count.begin()+k, count.end(), greater<int>()); //堆排序,时间复杂度为O(klogn)
            //注意默认为增序排列,这里要找前k大的数,故比较函数应设置为greater
           
           
       
            //程序时间复杂度为O(n+klogn)
        }
    };*/
     
  • 相关阅读:
    42 【docker】run命令
    41 【docker】初识
    37 【kubernetes】搭建dashboard
    36 【kubernetes】coredns
    34 【kubernetes】安装手册
    35 【kubernetes】configMap
    33 【kebernetes】一个错误的解决方案
    25 【python入门指南】如何编写测试代码
    26【python】sprintf风格的字符串
    24 【python入门指南】class
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225959.html
Copyright © 2011-2022 走看看