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 frequency
TreeMap<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 order
int feq = hm.get(num);
// handle duplicate keys (*)
if (!tm.containsKey(feq))
// using an ArrayList, if feq is first seen, create a new list
tm.put(feq, new ArrayList<>());
// append value to the list
tm.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;
}
}
Leetcode 347. Top K Frequent Elements
最新推荐文章于 2023-01-03 18:23:53 发布