0

我有这样的数组:

int[] array = { 2, 4, 6, 8, -3, 8, 2, 7, 2, 4 };

我想知道哪个数字显示的时间最多(在这种情况下当然是 2),我该怎么做?

4

6 回答 6

2

我想下面的代码将在 Java 8 中发挥作用。

int[] array = { 2, 4, 6, 8, -3, 8, 2, 7, 2, 4 };
Arrays.stream(array).collect(Collectors.groupingBy(s -> s))
      .forEach((k, v) -> System.out.println(k + ": " + v.size()));

印刷:

2: 3
4: 2
8: 2
6: 1
7: 1
-3: 1
于 2014-10-07T23:26:25.410 回答
1

你可以做这样的算法:

Map<Integer, Integer> frequencies = new HashMap<>();
for (int n : array) {
  frequencies.put(n, frequencies.getOrDefault(n, 0) + 1); // Java 8
}

if (!frequencies.isEmpty()) {
  Integer bestMatch = null;
  Integer lastCount = null;
  for (Map.Entry<Integer,Integer> entry : frequencies.entrySet()) {
    Integer count = entry.getValue(); 
    if (null == lastCount || count > lastCount) {
      bestMatch = entry.getKey(); 
      lastCount = count;
    }
  }
  System.out.println("Most frequent value: " + bestMatch + " (found " + lastCount + " times)");
}
  • 我们首先计算一个值出现的次数
  • 我们在 map 中选择最大值并存储关联的键。
于 2014-10-07T23:29:08.240 回答
0

您可以构建一个映射整数到他们的计数的地图。在 Java 中,类似HashMap<Integer, Integer>. 浏览列表并检查 int 是否已经在地图中。如果是,则将其计数加 1,否则将其初始化为 1。然后,返回地图并找到计数最高的数字。

于 2014-10-07T23:23:32.377 回答
0

您需要创建频率分布并遍历数组。当您使用整数时,这很容易,因为它们可以直接用作键。

HashTable frequencyDistribution = new HashTable();
for(int i=0; i<array.length; i++) {
    int key = array[i];
    if( !frequencyDistribution.containsKey( key ) ) frequencyDistribution.add( key, 0 );
    frequencyDistribution[ key ]++;
}
int modeKey;
int modeCnt = int.MIN;
foreach(int key in frequencyDistribution.keys) {
    int cnt = frequencyDistribution[key];
    if( cnt > modeCnt ) modeKey = key;
}
print("Most frequent is: {0} as it appears {1} times.", modeKey, modeCnt);
于 2014-10-07T23:25:25.353 回答
0

您可以使用桶排序的桶填充步骤,然后线性扫描所有桶以获取最常出现的数字(您知道如何获取数组中的最大数字,对吗?)。底层数据结构不必是数组(这是最快的),您可以使用任何具有 key -> value 机制的东西,因为对于 BIG 范围,由于内存限制,数组可能无法使用,代价是速度较慢运行时间。

于 2014-10-07T23:26:40.953 回答
0
  1. 首先对它们进行排序
  2. 现在进入一个循环,看看数字是否重复
  3. 如果是这样,计算它重复的次数并存储其详细信息。
  4. 在整个循环中做同样的事情。如果任何其他号码有更多计数,只需用新号码替换您存储的详细信息。您可以将数字和计数等详细信息存储在单独的变量中。
于 2014-10-07T23:31:03.593 回答