Leetcode 347. Top K Frequent Elements

来源:互联网 发布:安卓阅读软件 编辑:程序博客网 时间:2024/06/02 06:09
public class Solution {    public List<Integer> topKFrequent(int[] nums, int k) {        // set the value of treemap as list to handle when several numbers share a same frequencyTreeMap<Integer, List<Integer>> tm = new TreeMap<>();HashMap<Integer, Integer> hm = new HashMap<>();for (int n : nums)    // count frequencies (*)hm.put(n, hm.getOrDefault(n, 0)+1);for (int num : hm.keySet()) {// get the frequency and set it as the key of the tree map// tree map sorts the key in an increasing orderint feq = hm.get(num);// handle duplicate keys (*)if (!tm.containsKey(feq))    // using an ArrayList, if feq is first seen, create a new listtm.put(feq, new ArrayList<>());// append value to the listtm.get(feq).add(num);}List<Integer> ret = new ArrayList<>();while (ret.size() < k) {Map.Entry<Integer, List<Integer>> entry = tm.pollLastEntry();ret.addAll(entry.getValue());}return ret;    }}

0 0
原创粉丝点击