分享

【LeetCode】347. Top K Frequent Elements 前 K 个高频元素(Medium)(JAVA)

 印度阿三17 2020-12-22

【LeetCode】347. Top K Frequent Elements 前 K 个高频元素(Medium)(JAVA)

题目地址: https:///problems/top-k-frequent-elements/

题目描述:

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 n is 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 高的元素。

提示:

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

解题方法

  1. 先用 map 把 nums[i] 和对应出现的次数存起来
  2. 然后就区最大 k 值的问题了,用一个最小堆,来取最大的 k 个值
  3. 这里用了 java 的 PriorityQueue 优先队列,前 K 个元素直接放进去,K 个之后的元素,如果堆顶元素的个数比当前元素个数小,把堆顶元素取出,把当前元素放进去
class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i  ) {
            Integer temp = map.get(nums[i]);
            if (temp == null) {
                map.put(nums[i], 1);
            } else {
                map.put(nums[i], 1   temp);
            }
        }
        PriorityQueue<int[]> queue = new PriorityQueue<>(k, (a, b) -> (a[1] - b[1]));
        int count = 0;
        for (Map.Entry<Integer, Integer> entry: map.entrySet()) {
            if (count < k) {
                queue.offer(new int[]{entry.getKey(), entry.getValue()});
                count  ;
            } else if (queue.peek()[1] < entry.getValue()) {
                queue.poll();
                queue.offer(new int[]{entry.getKey(), entry.getValue()});
            }
        }
        int[] res = new int[k];
        for (int i = res.length - 1; i >= 0; i--) {
            res[i] = queue.poll()[0];
        }
        return res;
    }
}

执行耗时:13 ms,击败了94.69% 的Java用户
内存消耗:40.8 MB,击败了97.34% 的Java用户

欢迎关注我的公众号,LeetCode 每日一题更新
来源:https://www./content-1-794201.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章