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

[leetcode]347. Top K Frequent Elements

时间:2016-05-28 12:57:08      阅读:202      评论: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: 

  • 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.

Subscribe to see which companies asked this question

 

Solution:

1.使用hashtable获取每个元素出现的次数

2.使用小根堆heap排序(priority queue实现),获取前K个出现次数最多的元素pair

3.输出,注意是小根堆,要reverse一下

 1 class CompareDist
 2 {
 3 public:
 4     bool operator()(pair<int, int> n1, pair<int, int> n2) 
 5     {
 6         return n1.second > n2.second;
 7     }
 8 };
 9 
10 class Solution {
11 public:
12     vector<int> topKFrequent(vector<int>& nums, int k) 
13     {
14         vector<int> ret;
15         unordered_map<int, int> htable;
16         
17         for (int key : nums) // get each key appears times
18             htable[key]++;
19 
20         priority_queue<pair<int, int>, vector<pair<int, int> >, CompareDist> sheap; // use min heap to get k biggest
21         for (auto elem : htable)
22         {
23             if (sheap.size() < k)
24             {
25                 sheap.push(elem);
26             }
27             else
28             {
29                 pair<int, int> heap_min = sheap.top();
30                 if (elem.second > heap_min.second)
31                 {
32                     sheap.pop();
33                     sheap.push(elem);
34                 }
35             }
36         }
37         
38         while (!sheap.empty())
39         {
40             pair<int, int> heap_min = sheap.top();
41             ret.push_back(heap_min.first);
42             sheap.pop();
43         }
44         reverse(ret.begin(), ret.end());
45         
46         return ret;
47     }
48 };

 

[leetcode]347. Top K Frequent Elements

标签:

原文地址:http://www.cnblogs.com/ym65536/p/5537052.html

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