347. 前 K 个高频元素(力扣)

题目**:

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按 任意顺序 返回答案。(力扣)

示例 1:

输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]

示例 2:

输入: nums = [1], k = 1
输出: [1]

哇!!这题对我来说有点难啊!!这出现了一个对Hashmap中value排序的函数。

1、首先通过哈希函数计算出每个元素出现的次数;

2、然后根据value对其中的键值对进行排序;(用到了小顶堆)


PriorityQueue<Integer> queue = new PriorityQueue<Integer>((a, b) -> map.get(a) - map.get(b));

for (Integer key : map.keySet()) {
	queue.add(key);
	System.out.println("key=" + key + "的个数是:" + map.get(key));
		}
for (int i = 0; i < map.size(); i++) {
	res[i] = queue.poll();
		}

在这里,我们可以利用堆的思想:建立一个小顶堆,然后遍历「出现次数数组」:

    如果堆的元素个数小于 kkk,就可以直接插入堆中。
    如果堆的元素个数等于 kkk,则检查堆顶与当前出现次数的大小。如果堆顶更大,说明至少有 k 个数字的出现次数比当前值大,故舍弃当前值;否则,就弹出堆顶,并将当前值插入堆中。

3、最后遍历,存入数组中即可。

1、自定义输入输出值:

public class likou347 {
	public static void main(String[] args) {
//		先输入数组
		Scanner scanner = new Scanner(System.in);
		String[] s = scanner.nextLine().split(" ");
		int[] nums = new int[s.length];
		for (int i = 0; i < nums.length; i++) {
			nums[i] = Integer.parseInt(s[i]);
		}
//		然后输入整数k
		int k = scanner.nextInt();
		int[] res = new int[k];

//   统计哈希表中各个数出现的次数
		HashMap<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < nums.length; i++) {
			int index = map.getOrDefault(nums[i], 0);
			map.put(nums[i], index + 1);
		}

//      建立小顶堆
		PriorityQueue<Integer> queue = new PriorityQueue<Integer>((a, b) -> map.get(a) - map.get(b));

//      遍历哈希表,如果queue中的数的个数小于等于k则存入。
		for (Integer key : map.keySet()) {
			queue.add(key);
			if (queue.size() > k) {
				queue.poll();
			}
		}
		for (int i = 0; i < k; i++) {
			res[i] = queue.poll();
		}
//      输出数组,一定得转化一下,不然输出的只是地址。
		System.out.println(Arrays.toString(res));

	}

}

2、力扣答案

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        int[] res = new int[k];
		HashMap<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < nums.length; i++) {
			int index = map.getOrDefault(nums[i], 0);
			map.put(nums[i], index + 1);
		}


		PriorityQueue<Integer> queue = new PriorityQueue<Integer>((a, b) -> map.get(a) - map.get(b));

		for (Integer key : map.keySet()) {
			queue.add(key);
			if (queue.size() > k) {
				queue.poll();
			}
		}
		for (int i = 0; i < k; i++) {
			res[i] = queue.poll();
		}
		return res;

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值