2013-12-10 44 views
0

我寫了一個方法來查找數組的模式編號,數組的長度是10,所以我在數組中有十個數字,所以大小已滿。我的問題是,如果模式是多個數字我如何修改我的代碼來顯示兩個數字!查找模式編號的方法

如果我的數組看起來像這樣[1,1,1,2,2,2,3,5,6,8]這種情況下的模式是1和2。在我的代碼中,它只打印它獲得的第一個模式。 所以它會打印模式是1

public static int arryMode (int [] randomList) { 
    int maxValue = 0; 
    int maxCount = 0; 

    for (int i = 0; i < randomList.length; ++i) { 
     int count = 0; 

     for (int j = 0; j < randomList.length; ++j) { 
      if (randomList[j] == randomList[i]) { 
       ++count; 
      } 
     } 

     if (count > maxCount) { 
      maxCount = count; 
      maxValue = randomList[i]; 
     } 
    } 

    return maxValue; 
} 

回答

0

你可以使用一個ArrayList<Integer>存儲模式的所有值。 ArrayList是一個對象,表現爲可調整大小的數組。每次你會找到一個新的模式,如果它的數量等於先前的最大數量,那麼你會把它添加到列表中。如果計數大於先前的最大計數,那麼您將清除列表,並將新模式添加到列表中。

閱讀Java tutorial on collections

1

您需要收集多個最大值,而不是在找到更大的最大計數值時替換maxValue,則需要從新的最大值開始。對於所有那些等於最大值的情況,需要額外的情況。

爲了不反覆添加最大值,查看新的randomList [i]是否已經處於最大值,和/或使用Set。

public static Set<Integer> arryMode(int[] randomList) { 
    Set<Integer> maxValues = new LinkedHashSet<>(10); 
    int maxCount = 0; 
    for (int i = 0; i < randomList.length; ++i) { 

     if (maxValues.contains(randomList[i])) { // Heuristic. 
      continue; 
     } 

     int count = 0; 
     for (int j = 0; j < randomList.length; ++j) { 
      if (randomList[j] == randomList[i]) { 
       ++count; 
      } 
     } 
     if (count > maxCount) { 
      maxCount = count; 
      maxValues.clear(); 
      maxValues.add(randomList[i]); 
     } else if (count == maxCount) { 
      maxValues.add(randomList[i]); 
     } 
    } 
    return maxValues; 
} 

隨着

for (int maxValue : maxValues) { ... } 
+0

我試着用此代碼工作,但我得到了編譯器錯誤表示,需要的是設置發現INT THX反正 –

+0

對不起它的另一種方式圓 –