如何找到数组中的C#模式? [英] How to find the Mode in Array C#?

查看:172
本文介绍了如何找到数组中的C#模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一个阵列模式。我知道我必须做嵌套循环检查每个值,看看经常出现在数组中的元素。然后,我都数不过来的时候出现的第二个元素的数量。在code以下无法正常工作,任何人都可以帮我请。

 的for(int i = 0; I< x.length;我++)
{
    X [I] ++;
    INT高= 0;
    的for(int i = 0; I< x.length;我++)
    {
        如果(X [I]>高)
        高= X [I]
    }
}


解决方案

使用嵌套的循环是不是解决这个问题的好办法。它将拥有的O运行时间(n ^ 2) - 比最优O(n)的差多了。

您可以通过分组相同的值,然后用最大的计数查找组LINQ做到这一点:

  INT模式= x.GroupBy(V => 5)
            .OrderByDescending(G => g.Count())
            。第一()
            。键;

这是既简单,更快捷。但是请注意,(不像LINQ到SQL)LINQ到对象只需要在第一个结果时,目前不优化OrderByDescending。它完全排序整个结果集是为O(n log n)的操作。

您可能希望这个O(n)的算法来代替。它首先遍历一次通过组发现的最大数量,然后再次找到那算不算第一个对应的按键:

  VAR组= x.GroupBy(V => 5);
INT MAXCOUNT = groups.Max(G => g.Count());
INT模式= groups.First(G => g.Count()== MAXCOUNT)。重点;

您也可以使用<$c$c>MaxBy从MoreLINQ方法扩展,进一步提高了解决方案,这样只需要通过所有元素进行迭代一次。

I want to find the Mode in an Array. I know that I have to do nested loops to check each value and see how often the element in the array appears. Then I have to count the number of times the second element appears. The code below doesn't work, can anyone help me please.

for (int i = 0; i < x.length; i ++)
{
    x[i]++;
    int high = 0;
    for (int i = 0; i < x.length; i++)
    {
        if (x[i] > high)
        high = x[i];
    }
}

解决方案

Using nested loops is not a good way to solve this problem. It will have a run time of O(n^2) - much worse than the optimal O(n).

You can do it with LINQ by grouping identical values and then finding the group with the largest count:

int mode = x.GroupBy(v => v)
            .OrderByDescending(g => g.Count())
            .First()
            .Key;

This is both simpler and faster. But note that (unlike LINQ to SQL) LINQ to Objects currently doesn't optimize the OrderByDescending when only the first result is needed. It fully sorts the entire result set which is an O(n log n) operation.

You might want this O(n) algorithm instead. It first iterates once through the groups to find the maximum count, and then once more to find the first corresponding key for that count:

var groups = x.GroupBy(v => v);
int maxCount = groups.Max(g => g.Count());
int mode = groups.First(g => g.Count() == maxCount).Key;

You could also use the MaxBy extension from MoreLINQ method to further improve the solution so that it only requires iterating through all elements once.

这篇关于如何找到数组中的C#模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆