We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1db6b90 commit eb9795fCopy full SHA for eb9795f
1 file changed
top-k-frequent-elements/chjung99.java
@@ -0,0 +1,34 @@
1
+class Solution {
2
+ public int[] topKFrequent(int[] nums, int k) {
3
+ Map<Integer, Integer> map = new HashMap<>();
4
+ int[] answer = new int[k];
5
+ int n = nums.length;
6
+ List<Data> result = new ArrayList<>();
7
+
8
+ for (int i = 0; i < n; i++) {
9
+ int key = nums[i];
10
+ if (map.get(key) == null) {
11
+ map.put(key, 1);
12
+ } else {
13
+ map.put(key, map.get(key) + 1);
14
+ }
15
16
+ for (int key: map.keySet()) {
17
+ result.add(new Data(key, map.get(key)));
18
19
+ result.sort((a, b) -> b.count() - a.count());
20
21
+ for (int i = 0; i < k; i++) {
22
+ answer[i] = result.get(i).key();
23
24
25
+ return answer;
26
27
28
+ record Data(
29
+ int key,
30
+ int count
31
+ ){}
32
+}
33
34
0 commit comments