Reputation: 23
I need to print out the numbers that are the most frequent elements in an array. Say that I have an int
array like this:
int[] array = {1, 2, 3, 3, 3, 5}
I will then need to print out 3, as that is the most frequent element. But, I also need to print out the element that appear as frequent. Lets say I have this array now:
int[] array = {1, 2, 3, 3, 3, 5, 5, 5, 6, 7, 7, 7}
I then need to print out (ordered) 3, 5 and 7, as all three off them are the most frequent elements together. So the output needs to look like this:
3
5
7
This is the code I have so far (it works for printing out only one off the most frequent numbers)
Arrays.sort(diceSumArray);
int maxCount = 1;
int index = 1;
int r = diceSumArray[0];
for (int i = 1; i < diceSumArray.length; i++) {
if (diceSumArray[i] == diceSumArray[i-1]) {
index++;
} else {
if (index > maxCount) {
maxCount = index;
r = diceSumArray[i-1];
}
index = 1;
}
}
// not sure where to put the print or if the code below is necessary
System.out.println(r);
if (index > maxCount) {
maxCount = index;
r = diceSumArray[diceSumArray.length -1];
}
Upvotes: 2
Views: 73
Reputation: 28414
A better way to do this would be using HashMap
to achieve a linear
time complexity, where you would iterate over the array, save the # of occurrences of each item, and return a list of those that occur the most:
private static List<Integer> getMostFreq(int[] arr){
List<Integer> list = new ArrayList<>();
if(arr == null || arr.length == 0)
return list;
HashMap<Integer, Integer> map = new HashMap<>();
for(int num : arr)
if(!map.containsKey(num))
map.put(num,1);
else
map.replace(num, map.get(num)+1);
int max = Integer.MIN_VALUE;
for(HashMap.Entry<Integer,Integer> item : map.entrySet())
if(item.getValue() > max)
max = item.getValue();
for(HashMap.Entry<Integer,Integer> item : map.entrySet())
if(item.getValue() == max)
list.add(item.getKey());
return list;
}
Upvotes: 1