Top K Frequent Elements
class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
// create hash map and count frequency of all elements O(n) {1:3, 2:2, 3:1}
// then sort the elements by value and get the top K elements
Map<Integer, Integer> map = new HashMap<>();
for (int i : nums) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
return map.entrySet()
.stream()
.sorted((a, b) -> b.getValue() - a.getValue())
.map(entry -> entry.getKey())
.limit(k)
.collect(Collectors.toList());
}
}Last updated