LeetCode347 前 K 个高频元素
LeetCode347 前 K 个高频元素
题目:给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
原题目链接:https://leetcode-cn.com/problems/top-k-frequent-elements/
方法一、优先级队列
使用HashMap来统计数组中各个数字的词频:
Map<Integer,Integer> map=new HashMap<>();
for(Integer num:nums) {
Integer i=map.get(num);
map.put(num, i==null?1:++i);
}
使用优先级队列PriorityQueue来选择频率前k个元素:
Queue<int[]> que=new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] m,int[] n) {
return m[1]-n[1];
}
});
for(Map.Entry<Integer, Integer> entry:map.entrySet()) {
int num=entry.getKey(),count=entry.getValue();
if(que.size()==k) {
if(que.peek()[1]<count) {
que.poll();
que.offer(new int[] {num,count});
}
}else {
que.offer(new int[] {num,count});
}
}
优先级队列PriorityQueue:
1、PriorityQueue 是基于优先堆的一个无界队列,这个优先队列中的元素可以默认自然排序或者通过提供的。
2、PriorityQueue 的大小是不受限制的,但在创建时可以指定初始大小(DEFAULT_INITIAL_CAPACITY =11)。当我们向优先队列增加元素的时候,队列大小会自动增加。
3、PriorityQueue 是非线程安全的,所以 Java 提供了 PriorityBlockingQueue(实现 BlockingQueue接口)用于Java 多线程环境。
4、通过堆实现,具体说是通过完全二叉树(complete binary tree)实现的小顶堆(任意一个非叶子节点的权值,都不大于其左右子节点的权值),也就意味着可以通过数组来作为 PriorityQueue 的底层实现。
方法:
1、添加元素:
add(E e) & offer(E e):
时间复杂度:logn
原因:加入一个元素,要进行优先堆的平衡。
2、取出堆顶元素:
poll():
时间复杂度:logn
原因:将堆顶元素取出,旋转产生新的堆顶。
peek():
时间复杂度:1
原因:查看堆顶,不取出。
代码:
class Solution {
public static int[] topKFrequent(int[] nums, int k) {
List<Integer> list=new ArrayList<>();
int[] res=new int[k];
Map<Integer,Integer> map=new HashMap<>();
for(Integer num:nums) {
Integer i=map.get(num);
map.put(num, i==null?1:++i);
}
Queue<int[]> que=new PriorityQueue<int[]>(new Comparator<int[]>() {
public int compare(int[] m,int[] n) {
return m[1]-n[1];
}
});
for(Map.Entry<Integer, Integer> entry:map.entrySet()) {
int num=entry.getKey(),count=entry.getValue();
if(que.size()==k) {
if(que.peek()[1]<count) {
que.poll();
que.offer(new int[] {num,count});
}
}else {
que.offer(new int[] {num,count});
}
}
for(int i=0;i<k;i++) {
res[i]=que.poll()[0];
}
return res;
}
}
总结:
1、词频分析用HashMap
2、遍历HashMap用Entry<K,V> ,因为HashMap底层用entry数组存储数据。
3、优先级队列的底层数据结构:数组(通过完全二叉树,生成优先堆)。
4、通过重写Comparator接口来重写排序的方法。