c# - 数组中出现次数最多的数

标签 c# algorithm

我有这个数组,我写了一个函数 MostFreq,它接受一个整数数组并返回 2 个值:数组中出现频率更高的数字及其出现频率 检查这段代码,我写了你的看法?有更好的方法吗?

static void Main()
{ 
    int [] M={4,5,6,4,4,3,5,3};
    int x;
    int f=MyMath.MostFreq(M,out x );
    console.WriteLine("the most Frequent Item = {0} with frequency = {1}",x,f);
}

=====

在数学课上

public static int MostFreq(int[] _M, out int x)
{
    //First I need to sort the array in ascending order
    int Max_Freq, No_Freq, i, k;
    Array.Sort(_M);                         
    k = _M[0];
    Max_Freq = 0; i = 0; x = 0;
    while (i < _M.Length)
    {
        //No_Freq= the frequency of the current number
        No_Freq = 0;
        //X here is the number which is appear in the array Frequently 
        while (k == _M[i])
        {
            No_Freq++;
            i++;
            if (i == _M.Length) 
                break;
        }
        if (No_Freq > Max_Freq)
        {
            //so it will be printed the same
            Max_Freq = No_Freq;
            x = k;
        }
        if (i < _M.Length) k = _M[i];
    }
    return (Max_Freq);
}

最佳答案

LINQ 起来。我知道这是在 VB 中,但您应该能够将其转换为 C#:

Dim i = From Numbers In ints _
            Group Numbers By Numbers Into Group _
            Aggregate feq In Group Into Count() _
            Select New With {.Number = Numbers, .Count = Count}

编辑:现在也在 C# 中:

var i = from numbers in M
                group numbers by numbers into grouped
                select new { Number = grouped.Key, Freq = grouped.Count()};

关于c# - 数组中出现次数最多的数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/279359/

相关文章:

algorithm - 在小人计算中设计一个算法输入3个数字然后输出最高的

java - 如何将 2d 阵列旋转小于 90°,以获得最佳近似值?

c# - C# 析构函数的示例使用

c# - 如何使用 LINQ to XML 从示例 XML 中获取值

c# - 强制使用属性与类字段交互,即使该字段已公开

c# - 增加 jQuery/Javascript 中的 POST 数据大小

java - 在给定矩阵中搜索值密度的最佳方法是什么?

c# - Azure:表脚本不是由 sql 执行触发的

arrays - 构造第二个数组算法

python - 寻找一种更有效的方法在 Python 中重组大量 CSV