天天看点

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;
    }
}
           
Java,LeetCode 347. 前K个高频元素