如何找到数组中的C#模式?

编程入门 行业动态 更新时间:2024-10-25 00:31:18
本文介绍了如何找到数组中的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)。重点;

您也可以使用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#模式?

本文发布于:2023-11-29 17:33:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647104.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   模式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!