The question goes:
Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at least one element and that every element in the array has a value between 0 and 100 inclusive. Break ties by choosing the lower value.
For example, if the array passed contains the values {27, 15, 15, 11, 27}, your method should return 15. (Hint: You may wish to look at the Tally program from earlier in this chapter to get an idea of how to solve this problem.)
Below is my code that almost works except for single-element arrays
public static int mode(int[] n)
{
Arrays.sort(n);
int count2 = 0;
int count1 = 0;
int pupular1 =0;
int popular2 =0;
for (int i = 0; i < n.length; i++)
{
pupular1 = n[i];
count1 = 0; //see edit
for (int j = i + 1; j < n.length; j++)
{
if (pupular1 == n[j]) count1++;
}
if (count1 > count2)
{
popular2 = pupular1;
count2 = count1;
}
else if(count1 == count2)
{
popular2 = Math.min(popular2, pupular1);
}
}
return popular2;
}
Edit: finally figured it out. Changed count1 = 0;
to count1 = 1;
everything works now!
You should use a hashmap for such problems. it will take O(n) time to enter each element into the hashmap and o(1) to retrieve the element. In the given code, I am basically taking a global max and comparing it with the value received on 'get' from the hashmap, each time I am entering an element into it, have a look:
hashmap has two parts, one is the key, the second is the value when you do a get operation on the key, its value is returned.
public static int mode(int []array)
{
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
int max = 1;
int temp = 0;
for(int i = 0; i < array.length; i++) {
if (hm.get(array[i]) != null) {
int count = hm.get(array[i]);
count++;
hm.put(array[i], count);
if(count > max) {
max = count;
temp = array[i];
}
}
else
hm.put(array[i],1);
}
return temp;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With