Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9fd2c65

Browse files
authored
Create 347TopKFrequentElements..java
1 parent a07bc37 commit 9fd2c65

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

java/347TopKFrequentElements..java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public int[] topKFrequent(int[] nums, int k) {
3+
//hashmap, check count == k, add to result
4+
//List<Integer> result = new ArrayList();
5+
HashMap<Integer, Integer> map = new HashMap();
6+
//int max = 0;
7+
8+
for (int idx=0;idx<nums.length;idx++){
9+
int num = nums[idx];
10+
11+
map.put(num, map.getOrDefault(num,0)+1);
12+
13+
//max = Math.max(max, map.get(num));
14+
}
15+
List<Integer> set = new ArrayList<Integer>(map.keySet());
16+
List<Integer>[] out = new List[nums.length+1];
17+
18+
for (int idx=0;idx<set.size();idx++){
19+
int count = map.get(set.get(idx));
20+
21+
//if (count )
22+
if (out[count] == null)out[count] = new ArrayList<Integer>();
23+
24+
out[count].add(set.get(idx));
25+
}
26+
27+
int[] result = new int[k];
28+
int i=0;
29+
for (int idx=out.length-1;i<k;idx--) {
30+
if (out[idx] == null) continue;
31+
32+
for (Integer temp : out[idx]){
33+
if (i>=k) break;
34+
35+
result[i++]= temp;
36+
}
37+
}
38+
return result;
39+
}
40+
}

0 commit comments

Comments
 (0)