gpt4 book ai didi

java - 打印最大重复值

转载 作者:搜寻专家 更新时间:2023-11-01 02:18:58 27 4
gpt4 key购买 nike

我想打印数组中重复次数最多的值。如果两个值重复了最大次数,则打印最大的一个。我不知道如何打印最大的一个。我试过这个。它只是打印数组中重复次数最多的值。

int[] a= { 3,2,3,2,2};
int count = 1, tempCount;
int repeated = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
repeated = temp;
count = tempCount;
}
}
System.out.println(repeated);

如果假设数组元素是“3,2,3,3,2,4,5,4,6,4”那么它必须打印 4.(3 次 3 次和 4 次 3 次。 ....但是 4 是最大的数所以输出是 4)。现在我该如何更改我的代码?

最佳答案

这里:

repeated = temp;

您找到了一个“新的”重复值,并且您无条件地分配了它。

你需要区分两种情况:

if (tempCount == count && temp > repeated)
{
// updates for EQUAL count, but only for larger numbers
repeated = temp;
count = tempCount;
}
if (tempCount > count)
{
// updates for larger count, small/large value doesn't matter
repeated = temp;
count = tempCount;
}

解决你的问题!

关于java - 打印最大重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56793276/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com