Print maximum repeated value

Harini :

I want to print the most repeated value in an array. If two values get repeated for maximum number of times, then print the largest one.I don't know how to print the largest one.I tried this.It just prints the print the most repeated value in an array.

int[] a= { 3,2,3,2,2};
        int count = 1, tempCount;
  int repeated = 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)
    {
     repeated = temp;
      count = tempCount;
    }
  }
  System.out.println(repeated);

If suppose the array elements are "3,2,3,3,2,4,5,4,6,4" then it has to print 4.(no. 3 three times and no. 4 three times.....But 4 is the greatest no. so the output is 4). Now how can i change my code?

Dinnerspy :

change the j in this code to equal 0

for (int j = 1; j < a.length; j++)

as it skips the first element of the array which causes 3 to only be counted twice. also this logic should help if a number that is bigger has equal count

    int[] a= {3,2,3,2,2, 2, 4, 4, 5 ,5};
        int count = 1, tempCount;
        int repeated = a[0];
       int temp = 0;
       for (int i = 0; i < (a.length - 1); i++)
        {
       temp = a[i];
       tempCount = 0;
      for (int j = 0; j < a.length; j++)
    {
      if (temp == a[j])
        tempCount++;
    }
    if (tempCount ==count )
    {
        if(temp>repeated ){

     repeated = temp;
      count = tempCount;
        }
    }
    if (tempCount > count)
    {
     repeated = temp;
      count = tempCount;
    }
  }
    System.out.println(repeated);
    }
}

Edit i know its lazy but i kept it in the posters code format.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=121816&siteId=1