Skip to content

Commit 26dad0e

Browse files
committed
k most occurred using bucket method
1 parent 43e65bd commit 26dad0e

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

HashMap/kmostOccured.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
//Find Top K Most Frequent Numbers in an Array
2+
3+
public class kmostOccured {
4+
5+
public static List<Integer> kMostFrequent(int[] nums, int k) {
6+
7+
8+
Map<Integer, Integer> countMap = new HashMap<>();
9+
10+
int maxFreq = 0;
11+
12+
13+
for(int i = 0; i < nums.length; i++) {
14+
15+
16+
int freq = countMap.getOrDefault(nums[i],0)+1;
17+
18+
countMap.put(nums[i], freq);
19+
20+
maxFreq = Math.max(maxFreq, freq);
21+
}
22+
23+
List<Integer>[] bucket = new List[maxFreq + 1];
24+
25+
for(int n : countMap.keySet())
26+
{
27+
int freq = countMap.get(n);
28+
29+
if(bucket[freq]==null)
30+
bucket[freq] = new ArrayList<>();
31+
32+
bucket[freq].add(n);
33+
}
34+
35+
List<Integer> res = new ArrayList<>();
36+
37+
for(int i = bucket.length-1; i >= 0 && k>0; i--)
38+
{
39+
if(bucket[i]!=null)
40+
{
41+
List<Integer> list = bucket[i];
42+
res.addAll(list);
43+
k-= list.size();
44+
}
45+
}
46+
47+
return res;
48+
}
49+
50+
public static void main(String[] args) {
51+
int[] arr = {1, 1, 1, 2, 2, 3, 3, 3};
52+
List<Integer> result = kMostFrequent(arr, 2);
53+
54+
for(Integer elem : result) {
55+
System.out.print(elem + " ");
56+
}
57+
}
58+
}

0 commit comments

Comments
 (0)