zoukankan      html  css  js  c++  java
  • LeetCode 347. Top K Frequent Elements 前 K 个高频元素 (Java)

    题目:

    Given a non-empty array of integers, return the k most frequent elements.

    Example 1:

    Input: nums = [1,1,1,2,2,3], k = 2
    Output: [1,2]
    

    Example 2:

    Input: nums = [1], k = 1
    Output: [1]

    Note:

    • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
    • Your algorithm's time complexity must be better than O(n log n), where nis the array's size.
    • It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique.
    • You can return the answer in any order.

    分析:

    找出前K个高频元素,TopK的问题一般都可以利用堆,或者优先级队列来处理,统计好每个元素出现的顺序,加入到容量大小为k的堆中,即可得到答案。

    程序:

    class Solution {
        public int[] topKFrequent(int[] nums, int k) {
            HashMap<Integer, Integer> map = new HashMap<>();
            for(int num:nums){
                int times = map.getOrDefault(num, 0);
                map.put(num, times+1);
            }
            PriorityQueue<Integer> minHeap = new PriorityQueue<>((a, b)->{
                return map.get(a) - map.get(b);
            });
            for(int num:map.keySet()){
                minHeap.offer(num);
                if(minHeap.size() > k)
                    minHeap.poll();
            }
            int[] res = new int[k];
            for(int i = 0; i < res.length; ++i){
                res[i] = minHeap.poll();
            }
            return res;
        }
    }
  • 相关阅读:
    DECLARE
    deallocvt
    科研院所
    jQuery Ajax 确定 form 表单 submit 提交成功
    Java实现 LeetCode 10 正则表达式匹配
    Java实现 LeetCode 10 正则表达式匹配
    Java实现 LeetCode 9 回文数
    Java实现 LeetCode 9 回文数
    Java实现 LeetCode 9 回文数
    Java实现 LeetCode 8 字符串转换整数(atoi)
  • 原文地址:https://www.cnblogs.com/silentteller/p/12804164.html
Copyright © 2011-2022 走看看