zoukankan      html  css  js  c++  java
  • LeetCode347_TopK

    利用map先统计一下元素的频率;

    利用优先队列,求前K大频率,注意使用最小堆(维护一个元素个数k个的最小堆);

    重新设置比较器为greater,即最小堆。因为优先队列默认是最大堆less;

    另外对于队列元素是pair,需要了解比较规则为先比较first再比较second;

     1 // 347. Top K Frequent Elements
     2 // https://leetcode.com/problems/top-k-frequent-elements/description/
     3 // 时间复杂度: O(nlogk)
     4 // 空间复杂度: O(n + k)
     5 class Solution {
     6 public:
     7     vector<int> topKFrequent(vector<int>& nums, int k) {
     8         unordered_map<int,int> freq; //元素-频率
     9         for(int i = 0; i<nums.size(); i++){
    10             freq[nums[i]]++;
    11         }
    12         //要用到最小堆,C++默认是最大堆less
    13         priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq;
    14         for(unordered_map<int,int>::iterator itr = freq.begin(); itr != freq.end(); itr++){
    15             if(pq.size()==k){
    16                 if(itr->second > pq.top().first){
    17                     pq.pop();
    18                     pq.push(make_pair(itr->second,itr->first));
    19                 }
    20             }
    21             else {
    22                 pq.push(make_pair(itr->second,itr->first));
    23             }
    24         }
    25         vector<int> res;
    26         while(!pq.empty()){
    27             res.push_back(pq.top().second);
    28             pq.pop();
    29         }
    30         return  res;
    31     }
    32 };
  • 相关阅读:
    Bresenham画线算法
    DDA算法
    GL_LINES & GL_LINE_STRIP & GL_LINE_LOOP
    贝塞尔曲线
    弱引用
    Lambert模型
    ShadowVolume
    Phong Shading
    求反射向量
    Vertex Modifier of Surface Shader
  • 原文地址:https://www.cnblogs.com/grooovvve/p/12367281.html
Copyright © 2011-2022 走看看