class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
//先统计每个数字出现的频率
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length ; i++)
{
if(map.containsKey(nums[i]))
{
map.put(nums[i], map.get(nums[i]) + 1);
}
else
{
map.put(nums[i] , 1);
}
}
//根据出现的次数构造小顶堆,把次数少的放在堆顶
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>()
{
public int compare(Integer a, Integer b)
{
return map.get(a) - map.get(b);
}
});
for(int key : map.keySet())
{
if(pq.size() < k)
{
pq.add(key);
}
else if(map.get(key) > map.get(pq.peek()))
{
pq.remove();//直接删除,因为只需要K个
pq.add(key);
}
}
List<Integer> res = new ArrayList<>();
while (!pq.isEmpty())
{
res.add(pq.remove());
}
return res;
}
}