数组中最常见的数字

11 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);
}
Run Code Online (Sandbox Code Playgroud)

=====

在Mymath班

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);
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*n W 9

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}
Run Code Online (Sandbox Code Playgroud)

编辑:现在也在C#中:

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


Fly*_*wat 5

假设你不能使用LINQ,我可能会像这样接近算法:

  • 创建键/值字典
  • 迭代你的数组,为每个唯一元素添加一个字典,每次重复元素时增加值.
  • 走字典键,返回最高值的元素.

这不是一个很好的解决方案,但它很简单,ContainsKey是一个O(1)查找,所以你最多会迭代你的数组两次.