zoukankan      html  css  js  c++  java
  • 347. Top K Frequent Elements

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

    给出一个不为空的整数数组,返回出现频率前k位的数字。

    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. //你可以假设k总是有效的。
      • Your algorithm's time complexity must be better than O(n log n), where n is the array's size. //你算法复杂度必须比O(nlogn)更好。

    1、考虑使用map,但是时间会超出,改用没有顺序的unordered_map。

    2、使用优先队列,找出出现频率前k位的数。

    注意:下面给出的算法得出的结果并没有严格的排序,比如2出现的次数比3多,但是在res中,可能3排在2前面。

     1 class Solution {
     2 public:
     3     vector<int> topKFrequent(vector<int>& nums, int k) {
     4         unordered_map<int,int> map;
     5         for(int num : nums){
     6             map[num]++;
     7         }
     8         
     9         vector<int> res;
    10         priority_queue<pair<int,int>> pq; 
    11         for(auto it = map.begin(); it != map.end(); it++){
    12             pq.push(make_pair(it->second, it->first));
    13             if(pq.size() > (int)map.size() - k){
    14                 res.push_back(pq.top().second);
    15                 pq.pop();
    16             }
    17         }
    18         return res;
    19     }
    20 };
  • 相关阅读:
    BZOJ 1004: [HNOI2008]Cards [Polya 生成函数DP]
    BZOJ 1119: [POI2009]SLO [置换群]
    POJ 2154 Color [Polya 数论]
    POJ 2409 Let it Bead [置换群 Polya]
    POJ置换群入门[3/3]
    [置换群&Polya计数]【学习笔记】
    查看linux中的TCP连接数
    SIT测试 和 UAT测试
    原生app是什么意思?
    线程池原理
  • 原文地址:https://www.cnblogs.com/Z-Sky/p/5655479.html
Copyright © 2011-2022 走看看