LeetCode #347. Top K Frequent Element
Published: (January 31, 2026 at 04:49 AM EST)
1 min read
Source: Dev.to
Source: Dev.to
Complexity Analysis
- Time Complexity: O(n log n) (dominated by sorting)
- Space Complexity: O(n) for the HashMap and List
Solution
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map map = new HashMap<>();
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
}
List list = new ArrayList<>(map.keySet());
list.sort((a, b) -> Integer.compare(map.get(b), map.get(a)));
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = list.get(i);
}
return result;
}
}