给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
提示:
你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
你可以按任意顺序返回答案。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:使用Map统计每个数值出现的顺序,使用PriorityQueue(大顶推)统计前k个高频元素,放入数组中返回
class Solution {
@SuppressWarnings("unlikely-arg-type")
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> map=new HashMap();
for(int i=0;i<nums.length;i++)
{
map.put(nums[i],map.getOrDefault(nums[i],0)+1);
}
PriorityQueue<int[]> pq=new PriorityQueue(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
// TODO Auto-generated method stub
return o2[1]-o1[1];
}
});
for(Integer num:map.keySet())
{
pq.offer(new int[] {num,map.get(num)});
}
k=Math.min(k, pq.size());
int []re=new int[k];
for(int i=0;i<k;i++)
{
re[i]=pq.poll()[0];
}
return re;
}
}