美文网首页
前 K 个高频元素

前 K 个高频元素

作者: 二进制的二哈 | 来源:发表于2019-12-29 13:40 被阅读0次

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

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

示例 1:

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

示例 2:

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

说明:

  • 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。
  • 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。

利用优先队列(小根堆)的解法:

class Solution {

    class Node{
        int count;
        int key;
        public Node(int count,int key){
            this.count = count;
            this.key = key;
        }
    }

    public List<Integer> topKFrequent(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int num : nums){
            Integer count = map.get(num);
            if (count == null){
                map.put(num,1);
            }else {
                map.put(num,count+1);
            }
        }
        PriorityQueue<Node> queue = new PriorityQueue<>((n1,n2)->n1.count-n2.count);
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            queue.add(new Node(entry.getValue(),entry.getKey()));
            if (queue.size() > k)
                queue.poll();
        }
        List<Integer> ans = new ArrayList<>();
        while(!queue.isEmpty()){
            Node node = queue.poll();
            ans.add(node.key);
        }
        return ans;
    }
}

相关文章

  • 347. 前 K 个高频元素

    347. 前 K 个高频元素

  • 前K个高频元素

    给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 说明: 你可以假设给定的 k 总是合理的,且 1 ≤ ...

  • 前K个高频元素

    给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 示例 1: 输入: nums = [1,1,1,2,2...

  • 前 K 个高频元素

    题目来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/top-...

  • 前K个高频元素

    题目描述:给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 示例:输入: nums = [1,1,1,2...

  • LeetCode 栈、队列、优先队列专题 6:优先队列也是队列

    例题:LeetCode 第 347 题:前K个高频元素 传送门:347. 前K个高频元素。 给定一个非空的整数数组...

  • 算法笔记

    子序列 LC128. 最长连续序列 TOPK LC347. 最K个高频元素 LC347. 前K个高频元素 LC21...

  • LeetCode 347 前 K 个高频元素

    347. 前 K 个高频元素 这次是求前K个高频元素,同理,用堆其实最好解决,具体的步骤是:1.先建立一个hash...

  • 347前K个高频元素

    题目描述 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 示例 1: 输入: nums = [1,1,...

  • 【leetcode】前 K 个高频元素

    【leetcode】前 K 个高频元素 题目: 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 示例 ...

网友评论

      本文标题:前 K 个高频元素

      本文链接:https://www.haomeiwen.com/subject/xtuyoctx.html