首页 > 其他 > 详细

[leetcode]Heap-347. Top K Frequent Elements

时间:2018-01-13 19:50:46      阅读:221      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!