`

Top K Frequent Elements

 
阅读更多

 

import java.util.*;

public class Solution {

    public List<Integer> topKFrequent(int[] nums, int k) {

        HashMap<Integer, Integer> numberOccur = getNumOccur(nums);

        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>((o1, o2) -> numberOccur.get(o1) - numberOccur.get(o2));

        Set<Map.Entry<Integer, Integer>> entries = numberOccur.entrySet();
        for(Map.Entry<Integer, Integer> entry:entries){
            priorityQueue.add(entry.getKey());
            if(priorityQueue.size()>k){
                priorityQueue.poll();
            }
        }
        ArrayList<Integer> result = new ArrayList<>();

        for (int i = 0; i < k; i++) {
            result.add(priorityQueue.poll());
        }
        Collections.reverse(result);
        return result;
    }

    private HashMap<Integer, Integer> getNumOccur(int[] nums) {
        HashMap<Integer, Integer> numberOccur = new HashMap<>();
        for (int num : nums) {
            if (numberOccur.get(num) == null) {
                numberOccur.put(num, 0);
            }
            numberOccur.put(num, numberOccur.get(num) + 1);
        }
        return numberOccur;
    }

}

 

分享到:
评论

相关推荐

    leetcode530-leetcode:力扣在线评委

    Frequent Elements 2016.06.03 319. Bulb Switcher 343. Integer Break 268. Missing Number 144. Binary Tree Preorder Traversal 2016.06.06 94. Binary Tree Inorder Traversal 318. Maximum Product of Word ...

    LeetCode最全代码

    462 | [Minimum Moves to Equal Array Elements II](https://leetcode.com/problems/minimum-moves-to-equal-array-elements-ii/) | [C++](./C++/minimum-moves-to-equal-array-elements-ii.cpp) [Python](./Python/...

    javalruleetcode-reverie:找工作

    java lru leetcode Java相关知识 基础知识 集合 ...Elements(堆排序、桶排序) LintCode 532 Reverse Pairs(归并排序的应用)(面试题51:数组中的逆序对) LeetCode 315 Count of Smaller Numbers A

    Leetcode:一些关于算法的经典leetcode问题和面试问题

    "最大堆" 和 "最小堆" 在 LeetCode 中的应用包括 "Kth 最大元素" 和 "Top K Frequent Elements"。 7. **滑动窗口**: - 滑动窗口在数组或字符串问题中十分常见,用于找到固定大小窗口内的最大值、最小值或满足特定...

    leetcode2sumc-leetcode:leetcode

    [golang](./algorithms/Top_K_Frequent_Elements.go) 中等的 1 [两个和]() [Python](./Two_Sum.py) 中等的 2 [加两个数]() [python](./Add_Two_Numbers.py) 中等的 3 [无重复字符的最长子串]() [python](./Longest_...

Global site tag (gtag.js) - Google Analytics