Skip to content

Commit f8b6161

Browse files
committed
Java solution 347
1 parent 33c00eb commit f8b6161

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

java/_347TopKFrequentElements.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.*;
2+
3+
/**
4+
* Given a non-empty array of integers, return the k most frequent elements.
5+
* <p>
6+
* For example,
7+
* Given [1,1,1,2,2,3] and k = 2, return [1,2].
8+
* <p>
9+
* Note:
10+
* You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
11+
* Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
12+
* <p>
13+
* Created by drfish on 15/06/2017.
14+
*/
15+
public class _347TopKFrequentElements {
16+
public List<Integer> topKFrequent(int[] nums, int k) {
17+
List<Integer> result = new ArrayList<>();
18+
Map<Integer, Integer> map = new HashMap<>();
19+
PriorityQueue<Map.Entry<Integer, Integer>> maxHeap = new PriorityQueue<>((n1, n2) -> n2.getValue() -
20+
n1.getValue());
21+
for (int num : nums) {
22+
map.put(num, map.getOrDefault(num, 0) + 1);
23+
}
24+
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
25+
maxHeap.offer(entry);
26+
}
27+
while (k > 0) {
28+
k--;
29+
result.add(maxHeap.poll().getKey());
30+
}
31+
return result;
32+
}
33+
34+
public static void main(String[] args) {
35+
_347TopKFrequentElements solution = new _347TopKFrequentElements();
36+
assert Arrays.asList(1, 2).equals(solution.topKFrequent(new int[]{1, 1, 1, 2, 2, 3}, 2));
37+
}
38+
}

0 commit comments

Comments
 (0)