栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

leetcode347. 前 K 个高频元素

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode347. 前 K 个高频元素

1.题目描述:

给你一个整数数组nums和一个整数k,请你返回其中出现频率前k高的元素。你可以按任意顺序返回答案。

2.使用hashmap统计频次,再对value值进行排序(treeset只能对key排序),采用逆序取前k个值(需要完全遍历entryset排序),相当于大顶堆,时间复杂度O(nlogn)。

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map map = new HashMap<>();
        for (int i : nums) {
            if (map.containsKey(i)) map.put(i, map.get(i) + 1);
            else map.put(i, 1);
        }
        //PriorityQueue> pq = new PriorityQueue<>((o1, o2) -> o2.getValue() - o1.getValue());
        PriorityQueue> pq = new PriorityQueue<>(new Comparator>() {
            public int compare(Map.Entry entry1, Map.Entry entry2) {
                return entry2.getValue() - entry1.getValue();
            }
        });
        //pq.addAll(map.entrySet());
        for (Map.Entry entry : map.entrySet()) {
            pq.offer(entry);
        }
        int[] arr = new int[k];
        for (int i = 0 ; i < k; i++) {
            arr[i] = pq.poll().getKey();
        }
        return arr;
    }
}

3.使用hashmap统计频次,再对value值进行排序(treeset只能对key排序),采用顺序k个最大值(只维护k个entry的排序),相当于小顶堆,时间复杂度O(nlogk)。

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        Map map = new HashMap<>();
        for (int i : nums) {
            if (map.containsKey(i)) map.put(i, map.get(i) + 1);
            else map.put(i, 1);
        }
        PriorityQueue> pq = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
        for (Map.Entry entry : map.entrySet()) {
            pq.offer(entry);
            if (pq.size() > k) {
                pq.poll();//添加当前entry后每次移除最小元素
            }
        }
        int[] arr = new int[k];
        for (int i = 0 ; i < k; i++) {
            arr[i] = pq.poll().getKey();
        }
        return arr;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/921450.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号