哈希排序算法,【LeetCode】【HOT】347. 前 K 个高频元素(哈希表+优先队列)

 2023-09-25 阅读 32 评论 0

摘要:【LeetCode】【HOT】347. 前 K 个高频元素 文章目录【LeetCode】【HOT】347. 前 K 个高频元素 哈希排序算法, package hot;import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; import

【LeetCode】【HOT】347. 前 K 个高频元素

文章目录

  • 【LeetCode】【HOT】347. 前 K 个高频元素

哈希排序算法,在这里插入图片描述

package hot;import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;public class Solution347 {public static void main(String[] args) {int[] nums = {1,1,1,2,2,3};Solution347 solution = new Solution347();System.out.println(Arrays.toString(solution.method(nums, 2)));}private int[] method(int[] nums, int k){int[] res = new int[k];Map<Integer, Integer> map = new HashMap<>();Queue<Map.Entry<Integer, Integer>> heap = new PriorityQueue<>(new Comparator<Map.Entry<Integer, Integer>>() {@Overridepublic int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {return o2.getValue() - o1.getValue();}});for(int n : nums){if(map.containsKey(n)){map.put(n, map.get(n) + 1);}else{map.put(n, 1);}}for(Map.Entry<Integer, Integer> entry : map.entrySet()){heap.offer(entry);}for(int i = 0; i < k; i++){res[i] = heap.poll().getKey();}return res;}
}//时间复杂度为 O(mlogn)
//空间复杂度为 O(n)

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/95605.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息