-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathTopKFrequentElements.java
More file actions
39 lines (31 loc) · 1.19 KB
/
TopKFrequentElements.java
File metadata and controls
39 lines (31 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.*;
public class TopKFrequentElements {
public static int[] topKFrequent(int[] nums, int k) {
// Step 1: Count frequencies
Map<Integer, Integer> freqMap = new HashMap<>();
for (int num : nums) {
freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
}
// Step 2: Use a min-heap to keep top k elements
PriorityQueue<Map.Entry<Integer, Integer>> minHeap =
new PriorityQueue<>((a, b) -> a.getValue() - b.getValue());
for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) {
minHeap.offer(entry);
if (minHeap.size() > k) {
minHeap.poll(); // remove least frequent element
}
}
// Step 3: Extract elements from heap
int[] result = new int[k];
for (int i = k - 1; i >= 0; i--) {
result[i] = minHeap.poll().getKey();
}
return result;
}
public static void main(String[] args) {
int[] nums = {1, 1, 1, 2, 2, 3, 3, 3, 3, 4};
int k = 2;
int[] res = topKFrequent(nums, k);
System.out.println("Top " + k + " frequent elements: " + Arrays.toString(res));
}
}