码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Heap-347. Top K Frequent Elements

时间:2018-01-13 20:47:23      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:queue   val   post   vector   amp   blog   col   mos   class   

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: 

    • class Solution {
      public:
          vector<int> topKFrequent(vector<int>& nums, int k) {
              unordered_map<int,int> mp;
              for(auto &i : nums)
                  mp[i]++;
              priority_queue<pair<int,int>> pq;
              for(auto &i : mp) 
                  pq.push(make_pair(i.second, i.first));
              vector<int> res;
              while(k-- > 0 && !pq.empty()) {
                  res.push_back(pq.top().second);
                  pq.pop();
              }
              return res;
          }
      };

       

      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.

[leetcode]Heap-347. Top K Frequent Elements

标签:queue   val   post   vector   amp   blog   col   mos   class   

原文地址:https://www.cnblogs.com/chenhan05/p/8280249.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!