Top K Frequent Elements
Given an integer array nums and an integer k, return the k most frequent elements.
Use a hash map to count frequencies, then select the top k by frequency.
The output order can vary as long as the returned elements are the correct top-k set.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Example 3:
Input: nums = [4,4,4,5,5,6], k = 2
Output: [4,5]
Algorithm Flow

Recommendation Algorithm Flow for Top K Frequent Elements - Budibadu
Best Answers
java
import java.util.*;
class Solution {
public int[] top_k_frequent_elements(int[] nums, int k) {
Map<Integer, Integer> freq = new HashMap<>();
for (int x : nums) freq.put(x, freq.getOrDefault(x, 0) + 1);
List<Map.Entry<Integer, Integer>> arr = new ArrayList<>(freq.entrySet());
arr.sort((a, b) -> b.getValue() - a.getValue());
int[] res = new int[k];
for (int i = 0; i < k; i++) res[i] = arr.get(i).getKey();
return res;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
