Sorting by Frequency
Intuition
Count the frequency of each element using a hash map, then sort the unique elements by their frequency in descending order. The first k elements after sorting are the answer. This is a direct approach that leverages sorting to identify the top k elements.
Algorithm
- Build a frequency map counting how many times each element appears.
- Collect the unique elements and sort them by frequency in descending order.
- Return the first k elements from the sorted list.
O(n log n)SpaceO(n)Code (C++ · Java · Python · Go)
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> freq;
for (int num : nums) {
freq[num]++;
}
vector<pair<int, int>> freqList;
for (auto& [num, count] : freq) {
freqList.push_back({count, num});
}
sort(freqList.rbegin(), freqList.rend());
vector<int> result;
for (int i = 0; i < k; i++) {
result.push_back(freqList[i].second);
}
return result;
}
};class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> freq = new HashMap<>();
for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(freq.entrySet());
entries.sort((a, b) -> b.getValue() - a.getValue());
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = entries.get(i).getKey();
}
return result;
}
}def topKFrequent(nums: list[int], k: int) -> list[int]:
from collections import Counter
freq = Counter(nums)
sorted_items = sorted(freq.keys(), key=lambda x: freq[x], reverse=True)
return sorted_items[:k]import "sort"
func topKFrequent(nums []int, k int) []int {
freq := make(map[int]int)
for _, num := range nums {
freq[num]++
}
type pair struct {
num, count int
}
pairs := make([]pair, 0, len(freq))
for num, count := range freq {
pairs = append(pairs, pair{num, count})
}
sort.Slice(pairs, func(i, j int) bool {
return pairs[i].count > pairs[j].count
})
result := make([]int, k)
for i := 0; i < k; i++ {
result[i] = pairs[i].num
}
return result
}