Top k Frequent Elements
-
Intuition
-
Approach
-
Complexity
-
Code
Java
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
/* If i is already in the function map, then increment i's value by 1 else, add i to map with value = 1*/
for(int i: nums)
map.merge(i, 1, Integer::sum);
List<Integer> list = new ArrayList<>(map.keySet());
/* Sort by values in descending order */
list.sort((a, b) -> map.get(b) - map.get(a));
/* Take sublist, convert to int[] */
return list.subList(0, k).stream().mapToInt(Integer::intValue).toArray();
}
}