【问题标题】:I want to print the number with the highest frequency [duplicate]我想打印频率最高的数字[重复]
【发布时间】:2020-07-04 02:43:23
【问题描述】:

我想打印频率最高的数字。

例如

如果数组 = {1,2,2,3,4}

结果 = 2

这样……我怎么解决?!

【问题讨论】:

  • 让我们考虑一下。每个元素都需要跟踪它自己的出现次数。听起来像是字典的工作。
  • int[] 数组 = { 1, 2, 2, 3, 4 }; var 频率 = array.GroupBy(x => x).OrderByDescending(x => x.Count()).First().Key;
  • @MongZhu is this homework? 这无关紧要。
  • with linq: group by, order desc by count, 先取

标签: c# frequency


【解决方案1】:

你可以定义一个计数器并且你必须使用嵌套循环 很抱歉我不懂 C# 语法 因为我是用 Java 编写的

 public static double frequency(double[] arr)
    {
        int c = 0;
        int max = 1 ;
        double frequency = 0.0;
        for (int i = 0 ; i<arr.length ; i++)
        {
            for(int j = 0 ;j<arr.length ; j++)
            {
                if(arr[i] == arr[j])
                {
                    c++;
                }
            }
            if(c> max)
            {
                frequency = arr[i];
            }
            c=0;

        }
        return frequency;
    }

【讨论】:

  • 其实我同意你的观点,但是我不知道如何使用 StackOverflow 来提高自己,然后我学会了希望他学习如何使用 Stack 来提高自己的代码技能
猜你喜欢
  • 2021-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
相关资源
最近更新 更多