SexyMF SexyMF - 7 months ago 19
Java Question

Java - Find the most popular element in int[] array

int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};


how can I write a method and return 7?

Edit 1

I want to keep it native without the help of lists,maps or other helpers.

Only arrays[].

Thanks

Answer
public int getPopularElement(int[] a)
{
  int count = 1, tempCount;
  int popular = a[0];
  int temp = 0;
  for (int i = 0; i < (a.length - 1); i++)
  {
    temp = a[i];
    tempCount = 0;
    for (int j = 1; j < a.length; j++)
    {
      if (temp == a[j])
        tempCount++;
    }
    if (tempCount > count)
    {
      popular = temp;
      count = tempCount;
    }
  }
  return popular;
}

Hope this works for you.

Regards

Comments