-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTopKFrequentElements.java
35 lines (30 loc) · 1.21 KB
/
TopKFrequentElements.java
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
import java.util.Arrays;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TopKFrequentElements {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> memberFrequencyMap = Arrays.stream(nums)
.boxed()
.collect(Collectors.toMap(Function.identity(), v -> 1, Integer::sum));
PriorityQueue<Integer[]> priorityQueue = new PriorityQueue<>((a, b) -> -1*a[0].compareTo(b[0]));
memberFrequencyMap.entrySet().stream()
.map(entry -> {
Integer[] frequencyElement = new Integer[2];
frequencyElement[0] = entry.getValue();
frequencyElement[1] = entry.getKey();
return frequencyElement;
}).forEach(priorityQueue::add);
return IntStream.range(0, k)
.map(num -> (int)priorityQueue.poll()[1])
.toArray();
}
public static void main(String[] args) {
int array[] = {1};
TopKFrequentElements topKFrequentElements = new TopKFrequentElements();
var k = topKFrequentElements.topKFrequent(array, 1);
System.out.println(Arrays.toString(k));
}
}