【LeetCode笔记】347. 前K个高频元素(Java、优先队列、小顶堆、HashMap)
生活随笔
收集整理的這篇文章主要介紹了
【LeetCode笔记】347. 前K个高频元素(Java、优先队列、小顶堆、HashMap)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 題目描述
- 思路 & 代碼
- 更新版:引入 stream 流 + Lambda
題目描述
- 時間復雜度小于O(n*logn),否則直接sort,再遍歷就很輕松。
- 很有學習價值的題目,第一次使用了優先隊列PriorityQueue。
思路 & 代碼
- 首先遍歷數組,用HashMap存儲 元素值 - 頻率 映射
- 然后維護一個容量為 k 的小頂堆(重寫比較器,注意寫法),遍歷哈希表存入小頂堆中
- 接著把最終的小頂堆存入數組即可
更新版:引入 stream 流 + Lambda
class Solution {public int[] topKFrequent(int[] nums, int k) {Map<Integer, Integer> map = new HashMap<>();for(int temp : nums) {if(map.containsKey(temp)) {map.put(temp, map.get(temp) + 1);}else {map.put(temp, 1);}}PriorityQueue<Integer> queue = new PriorityQueue<>((Integer a, Integer b) -> (map.get(a) - map.get(b)));for(Map.Entry<Integer, Integer> entry : map.entrySet()) {if(queue.size() < k) {queue.add(entry.getKey());}else if(entry.getValue() > map.get(queue.peek())) {queue.remove();queue.add(entry.getKey());}}return queue.stream().mapToInt(Integer::valueOf).toArray();} }總結
以上是生活随笔為你收集整理的【LeetCode笔记】347. 前K个高频元素(Java、优先队列、小顶堆、HashMap)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring cloud alibaba
- 下一篇: 如何使用Python操作MySQL数据库