我有这样的数组:
int[] array = { 2, 4, 6, 8, -3, 8, 2, 7, 2, 4 };
我想知道哪个数字显示的时间最多(在这种情况下当然是 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
你可以做这样的算法:
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)");
}
您可以构建一个映射整数到他们的计数的地图。在 Java 中,类似HashMap<Integer, Integer>
. 浏览列表并检查 int 是否已经在地图中。如果是,则将其计数加 1,否则将其初始化为 1。然后,返回地图并找到计数最高的数字。
您需要创建频率分布并遍历数组。当您使用整数时,这很容易,因为它们可以直接用作键。
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);
您可以使用桶排序的桶填充步骤,然后线性扫描所有桶以获取最常出现的数字(您知道如何获取数组中的最大数字,对吗?)。底层数据结构不必是数组(这是最快的),您可以使用任何具有 key -> value 机制的东西,因为对于 BIG 范围,由于内存限制,数组可能无法使用,代价是速度较慢运行时间。