Finding Multiple Modes In An Array

前端 未结 4 1072
醉梦人生
醉梦人生 2021-01-22 10:38

I\'m trying to write a java method which finds all the modes in an array. I know there is a simple method to find the mode in an array but when there are more than one single mo

4条回答
  •  無奈伤痛
    2021-01-22 11:10

    The following code will return you an Integer[] containing the modes. If you need an int[] instead, you still need to convert the Integer instances to ints manually. Probably not the most efficient version, but its matches closely to your code

    public static Integer[] mode(int a[]){
      List modes = new ArrayList(  );
      int maxCount=0;   
      for (int i = 0; i < a.length; ++i){
        int count = 0;
        for (int j = 0; j < a.length; ++j){
          if (a[j] == a[i]) ++count;
        }
        if (count > maxCount){
          maxCount = count;
          modes.clear();
          modes.add( a[i] );
        } else if ( count == maxCount ){
          modes.add( a[i] );
        }
      }
      return modes.toArray( new Integer[modes.size()] );
    }
    

提交回复
热议问题