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

标签 java arrays digits

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/

相关文章:

javascript - 在 javascript ES5 中不从数组中获取未定义的项

python - numpy 沿轴应用,错误 "ValueError: could not broadcast input array from shape (2) into shape (1)"

matlab - 四舍五入到 n 位有效数字

ruby - 符号化字符串中的任何非数字(Ruby)

ios - 在 IOS 中将图像数组上传到服务器

c - 获取整数位数

java - 用单线程写 LMAX

java - Java 中的@Override 是什么?

java - 如何使用 Java 8 Lambdas 将对象列表转换为 Map<Object, Object>

java - FindBugs 警告 : Inefficient use of keySet iterator