2013-12-10 39 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

对不起它的另一种方式圆 –