gpt4 book ai didi

java编程和查找数组的模式

转载 作者:行者123 更新时间:2023-11-30 09:40:23 25 4
gpt4 key购买 nike

我有一个任务,我需要找到数组的模式。这意味着我正在寻找最常见的 int。我已经完成了,但任务还说如果有两种相同的模式,我应该返回最小的整数,例如 {1,1,1,2,2,2} 应该给 1(就像在我的文件中一样我使用那个数组,它给出了 2)

public class theMode
{
public theMode()
{
int[] testingArray = new int[] {1,1,1,2,2,2,4};
int mode=findMode(testingArray);
System.out.println(mode);
}

public int findMode(int[] testingArray)
{
int modeWeAreLookingFor = 0;
int frequencyOfMode = 0;

for (int i = 0; i < testingArray.length; i++)
{
int currentIndexOfArray = testingArray[i];
int frequencyOfEachInArray = howMany(testingArray,currentIndexOfArray);

if (frequencyOfEachInArray > frequencyOfMode)
{
modeWeAreLookingFor = currentIndexOfArray;
frequencyOfMode = modeWeAreLookingFor;

}
}
return modeWeAreLookingFor;
}

public int howMany(int[] testingArray, int c)
{
int howManyOfThisInt=0;
for(int i=0; i < testingArray.length;i++)
{
if(testingArray[i]==c){
howManyOfThisInt++;
}
}
return howManyOfThisInt;
}


public static void main(String[] args)
{
new theMode();
}
}

如您所见,我的算法返回最后找到的模式或我应该如何解释它。

最佳答案

我会以不同的方式处理它。使用 map ,您可以将每个唯一数字用作键,然后将计数用作值。遍历数组并为找到的每个数字检查映射以查看是否存在具有该值的键。如果找到一个,则将其值增加 1,否则创建一个值为 1 的新条目。

然后您可以检查每个 map 条目的值,看看哪个条目的计数最高。如果当前键的计数高于前一个键,则它是“当前”答案。但是您有可能使用具有相似计数的键,因此您需要存储每个“获胜”答案。

解决此问题的一种方法是检查每个映射的每个条目并删除每个小于当前最高计数的条目。您将剩下的是所有“最高计数”的 map 。如果您的 map 只有一个条目,那么它的键就是答案,否则您将需要比较一组键以确定最低的键。

关于java编程和查找数组的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9448950/

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