2016-05-04 15 views
-2

このコードは、単一モードが存在する場合にのみモードを取得できます。 2つのモードが存在する場合、-1を返す方法を知りたい。例えば:1 1 1 2 2 2 3とリターン-1はモードが存在しない場合に、1 2 3 4 5 6配列内のモードを見つける

public Long getMode() { 


     long [] num = this.getElements(); 

     long maxValue=0, maxCount=0; 
     for (int i = 0; i < num.length; ++i){ 
      long count = 0; 
      for (int j = 0; j < num.length; ++j){ 
       if (num[j] == num[i]) 
       ++count; 
      } 
      if (count > maxCount){ 
       maxCount = count; 
       maxValue = num[i]; 
      } 
     } 
     return maxValue; 
     } 
+0

の代わりに、あなたは 'で、カウントを格納することができた値を保持するために単一の値をint [10] '配列ですが、各要素は単一の数字の出現を表します。最後に配列の最大値を見つける必要があります。もしそれが2回以上存在するなら、 '-1 'を返すだけです。 – SomeJavaGuy

答えて

0

あなたのコードがある場合は、-1を返さないことを除いて、正常に動作しますモードがない場合、または2つのモードが存在する場合。このため

次のように、あなたはあなたのプログラムを変更することができます
(私は私が変更されたセクションをcomentedている)

public static Long getMode() { 

    long [] num = this.getElements(); 
    long maxValue=0, maxCount=0; 
    boolean err = false; // New vraible to check if there is an error. 
    for (int i = 0; i < num.length; ++i){ 
     long count = 0; 
     for (int j = 0; j < num.length; ++j){ 
      if (num[j] == num[i]) 
       ++count; 
     } 
     if(count==maxCount && maxValue!=num[i]){ // if there are two modes 
      err=true; // then set err to true. 
     }else if (count > maxCount){ 
      maxCount = count; 
      maxValue = num[i]; 
      err = false; // If valid mode is found, then set err to false. 
     } 
     System.out.println(err); 
    } 
    return err ? -1 : maxValue; // return value if err is false, else return -1 
} 
+0

ありがとう – Andrew

関連する問題