###### Rijkstra的专栏

https://github.com/Ray137076517

###### 【leetcode】Top K Frequent Elements

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.

• 统计每个数的出现频率，存在unordered_map中
• 定义一个vector<vector<int>>容器，将每个频率对应的数存在vector中
• 倒序遍历容器，依次将k个数存入结果容器中

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k)
{
unordered_map<int, int> dict;
vector<int> result;
for (auto n : nums)
++dict[n];
vector< vector<int> > freq(nums.size() + 1);
for (auto p : dict)
freq[p.second].push_back(p.first);
for (int i = freq.size() - 1; i >= 0 && result.size() < k; --i)
{
for (auto n : freq[i])
{
result.push_back(n);
if (result.size() == k)
break;
}
}
return result;
}
};

#### [leetcode] 347. Top K Frequent Elements

2016-05-03 20:25:22

#### 【LeetCode】347. Top K Frequent Elements——基于Java的解决方案

2016-05-31 22:43:35

#### 347. Top K Frequent Elements (C++程序实现，两种方案)

2016-05-04 10:46:35

#### leetcode_347 Top K Frequent Elements

2016-05-12 22:04:11

#### 【Leetcode】Top K Frequent Elements

2016-05-04 10:00:21

#### 347. Top K Frequent Elements [medium] (Python)

2016-07-30 21:04:11

#### 347. Top K Frequent Elements-获得前K高次元素

2016-05-04 22:46:24

#### LeetCode | 347. Top K Frequent Elements 优先队列技巧题

2018-01-13 13:42:15

#### 【LeetCode】692. Top K Frequent Words 解题报告（Python）

2018-03-14 20:17:16

#### LeetCode347—Top K Frequent Elements

2016-05-03 16:20:00

## 不良信息举报

【leetcode】Top K Frequent Elements