# 347. Top K Frequent Elements 前 K 个高频元素

@TOC

## # 题目描述

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:

1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
2. Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

## # 解题方法

### # 字典

``````from collections import Counter
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
counter = Counter(nums).most_common()
return [counter[i][0] for i in range(k)]
``````

### # 优先级队列

``````class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
map<int, int> m;
for (int n : nums) m[n] ++;
priority_queue<pair<int, int>> p;
for (auto a : m)
p.push({a.second, a.first});
vector<int> res;
for (int i = 0; i < k; i++) {
res.push_back(p.top().second); p.pop();
}
return res;
}
};
``````

## # 日期

2018 年 2 月 8 日 2018 年 12 月 14 日 —— 12月过半，2019就要开始