打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

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

题目地址: https://leetcode.com/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 = 2Output: [1,2]

Example 2:

Input: nums = [1], k = 1Output: [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.icode9.com/content-1-794201.html
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
[Leetcode] Remove Element 删除数组元素
​LeetCode刷题实战442:数组中重复的数据
野路子搞算法《两数之和》,带着小白刷面试算法题
LeetCode 347.前K个高频元素
查找数组中未出现的数
LeetCode 4. 寻找两个正序数组的中位数
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服