gpt4 book ai didi

java - 在数字数组中查找数字的 maxFreq 的输出未按预期输出

转载 作者:行者123 更新时间:2023-12-01 10:44:11 24 4
gpt4 key购买 nike

Given an array of numbers as input, return the digit which occurs the maximum number of times in the input.

我的方法

我首先分隔了数组中每个成员的每个数字。然后,我计算了每个数字的频率,然后找到了该数字出现的最大次数并记下了它的位置。当我在数字分隔数组中搜索位置时,我找到了出现次数最多的数字。

这是我尝试使用以下代码执行的操作:

 int[] seperateDigits(int[] numbers)
{

int c[]=new int[numbers.length*2];
for(int i=0;i<numbers.length;i++)
{
for(int k=0;numbers[i]>0;i++)
{

int q=numbers[i]%10; //used this logic for separation of digits
System.out.println(numbers[i]);

c[k]=q;
System.out.println(c[k]);
k++;
numbers[i]=numbers[i]/10;

}
}
return c;
}

int countMaxFreq(int c[])
{
int t[]=new int[c.length];
int count=1;
if(c.length<2)
return count;
else
{

//used the logic for finding maximum frequency of each digit.
int m=0;
for(int i=0;i<c.length;i++)
{
for(int j=i+1;j<c.length;j++)
{
if(c[j]==c[i])
{
count++;

}

}
t[m++]=count;

}
}
if(c.length<2)
return c[0];
else
{

int max=t[0];
int max_index=0;
for(int i=1;i<t.length;i++)
{
if(t[i]>=max) //used the logic for finding frequency.
{
max_index=i;
}
}
for(int l=0;l<c.length;l++)
{ //Return the position of the frequent element.
if(l==max_index)
{
break;
}
}
return max_index;
}
}
}

最佳答案

您可以简化此算法的方法:

  • 创建一个int[] counts = new int[10],最多有10位
  • 对于输入中的每个数字
    • 每个数字
    • 增加数字的数量
  • 找到最大元素,返回其索引,这就是您要查找的数字

例如:

if (numbers.length == 0) {
throw new NoSuchElementException("no numbers, so 'most frequent' makes no sense");
}

int[] counts = new int[10];

for (int num : numbers) {
if (num == 0) {
++counts[0];
} else {
num = Math.abs(num);
while (num > 0) {
int digit = num % 10;
num /= 10;
++counts[digit];
}
}
}

return IntStream.range(0, counts.length)
.reduce((i, j) -> counts[i] < counts[j] ? j : i)
.getAsInt();

注意:当多个数字的计数相同时,此实现将返回较小的数字。

关于java - 在数字数组中查找数字的 maxFreq 的输出未按预期输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34282587/

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