I have an ArrayList
in Java with values of
4, 4, 3, 3, 5, 6
and I need to find the most frequent value. If multiple values have the same number of occurrences, return the largest one.
So in the example above, I need to return the value 4.
private int getFrequentNumber(ArrayList<Integer> arr){
int popular = arr.get(0);
int count = 1;
int tempcount = 0;
int temp = 0;
for(int i = 0; i < arr.size(); i++) {
temp = arr.get(i);
tempcount = 0;
for(int j = 1; j < arr.size(); j++) {
if(temp == arr.get(j))
tempcount++;
}
if (tempcount > count) {
popular = temp;
count = tempcount;
}
}
return popular;
}
Right now I have this code so it returns the most frequent number but I need help returning the largest most frequent number.
Step1: QuickSort on ArrayList<Integer> arr
;
Step2: Iteration on ArrayList<Integer> arr
as you have done.