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

Leetcode P347 java使用优先队列+hashtable去解决

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

Leetcode P347 java使用优先队列+hashtable去解决

Leetcode P347 java使用优先队列+hashtable去解决 ideas

首先记录每个元素出现的个数

      HashMap map = new HashMap<>();
        for (int num : nums) {
            map.put(num,map.getOrDefault(num,0)+1);
        }

接下来设置队列排序规律要求按照出现次数从小到大排序

  PriorityQueue priorityQueue = new PriorityQueue<>((a,b) -> map.get(a) - map.get(b));

每次循环把最小的弹出,循环结束只剩下出现次数是前k的了

for (Integer integer : map.keySet()) {
    priorityQueue.offer(integer);
    if (priorityQueue.size() > k){
        priorityQueue.poll();
    }
}
code
package leccod;

import lancup.A;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class P347 {
    public static void main(String[] args) {
       int[] res = new P347().topKFrequent(new int[]{3,2,3,1,2,4,5,5,6,7,7,8,2,3,1,1,1,10,11,5,6,2,4,7,8,5,6}, 1);
        for (int re : res) {
            System.out.println(re);
        }
    }

    public int[] topKFrequent(int[] nums, int k) {
        int[] res = new int[k];
        //记录每个元素出现的个数
        HashMap map = new HashMap<>();
        for (int num : nums) {
            map.put(num,map.getOrDefault(num,0)+1);
        }

        //设置排序规律要求按照出现次数从小到大排序
        PriorityQueue priorityQueue = new PriorityQueue<>((a,b) -> map.get(a) - map.get(b));

        //每次循环把最小的弹出,循环结束只剩下出现次数是前k的了
        for (Integer integer : map.keySet()) {
            priorityQueue.offer(integer);
            if (priorityQueue.size() > k){
                priorityQueue.poll();
            }
        }

        for (int i = 0; i < k; i++) {
            res[i] = priorityQueue.poll();
        }

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

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

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