Java,LeetCode 347. 前K个高频元素

前K个高频元素

1. 题目描述

难易度:中等

给定一个非空的整数数组,返回其中出现频率前 k 高的元素。

示例 1:

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

示例 2:

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

提示

1. 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
2. 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。
3. 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。
4. 你可以按任意顺序返回答案。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/top-k-frequent-elements

2. 思路分析

  • 创建HashMap,将数组中元素个数进行统计
  • 创建优先级队列,重写构造器,让HashMap按值从大到小依次添加到队列中
  • 取出队列前K个元素加入数组中,即为需要的结果集
  • 详细过程见代码注释

3. 代码演示

/**
 * @Description: TODO
 * @Author YunShuaiWei
 * @Date 2020/7/5 19:10
 * @Version
 **/
public class Solution {
    public static void main(String[] args) {
        int[] nums = new int[]{1};
        Solution s = new Solution();
        int[] ints = s.topKFrequent(nums, 1);
        System.out.println(Arrays.toString(ints));
    }

    public int[] topKFrequent(int[] nums, int k) {
        HashMap<Integer, Integer> map = new HashMap<>();
        //将数组中的元素加入哈希表中,键为nums中的元素,值为该元素出现的次数
        for (int num : nums) {
            if (map.containsKey(num)) {
                Integer val = map.get(num) + 1;
                map.put(num, val);
            } else {
                map.put(num, 1);
            }
        }
        //将HashMap添加到堆中,按从大到小的顺序添加
        PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });
        //将HashMap加入到优先级队列中
        queue.addAll(map.entrySet());
        ArrayList<Integer> list = new ArrayList<>();
        int[] res = new int[k];
        //取前k个高频元素,并加入到数组中
        for (int i = 0; i < res.length; i++) {
            res[i] = Objects.requireNonNull(queue.poll()).getKey();
        }
        return res;
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ysw!不将就

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值