LeetCode347 前 K 个高频元素(优先级队列:PriorityQueue)

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接口来重写排序的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值