zoukankan      html  css  js  c++  java
  • leetcode 347. 前 K 个高频元素 java

    题目:

    给定一个非空的整数数组,返回其中出现频率前 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 是数组的大小。

    解题:

    首先遍历数组,并且用hashMap保存元素出现的次数,然后使用最小堆保存出现频率最高的K个元素

    class Solution {
        public List<Integer> topKFrequent(int[] nums, int k) {
            // 使用HashMap,统计每个元素出现的次数,元素为键,元素出现的次数为值
            HashMap<Integer,Integer> map = new HashMap();
            for(int num : nums){
                if (map.containsKey(num)) {
                    map.put(num, map.get(num) + 1);
                } else {
                    map.put(num, 1);
                }
            }
            // 遍历map,用最小堆保存频率最大的k个元素
            PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
                @Override
                public int compare(Integer a, Integer b) {
                    return map.get(a) - map.get(b);
                }
            });
            for (Integer key : map.keySet()) {
                if (pq.size() < k) {
                    pq.add(key);
                } else if (map.get(key) > map.get(pq.peek())) {
                    pq.remove();
                    pq.add(key);
                }
            }
            // 取出最小堆中的元素
            List<Integer> res = new ArrayList<>();
            while (!pq.isEmpty()) {
                res.add(pq.remove());
            }
            return res;
        }
    }
  • 相关阅读:
    HTML5 <input> multiple 属性
    AWS
    new Set() 数组去重
    IAM
    Amazon S3
    Promis 实例
    JS
    React 5
    React 4
    React 3
  • 原文地址:https://www.cnblogs.com/yanhowever/p/11649479.html
Copyright © 2011-2022 走看看