从大多数重复的数组中找到值 [英] find the value from an array which is repeated most times
本文介绍了从大多数重复的数组中找到值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
谁能告诉,从重复次数最多的数组中查找值的最佳方法
前
string [] array = new string [] {"1","2","2","3","3","4","2","3","4","4", "2","2",};
预期答案:2
解决方案
最佳"在什么意义上?
有很多种方法可以做到这一点,其中一些是:
1)一个foreach循环,将出现的次数计数到一个单独的数组或字典中.然后对我的实例进行排序,并获得最高价值.
2)使用Linq查询执行相同的操作.
3)对原始数组进行排序,然后循环遍历,计算出现的次数并随手挑选最大的数组.
我该怎么做?取决于要检查的数据以及其中有多少数据.
最好"是一个主观词-可能表示最快",最小",最清晰",最容易理解"甚至是最不易理解,因此没有人会碰它".
嗯,这也许不是最优雅的解决方案,但确实可以做到:
公共 字符串 GetMaxElementCount(字符串 []数组) { List< string> list = 新 List< string>(数组); IEnumerable< IGrouping<字符串,字符串>> g = list.GroupBy(i = > i); int countMax = 0 ; 字符串 keyMax = 字符串 .Empty; foreach (IGrouping< string,string> grp in g) { int count = grp.Count(); 如果(countMax < 计数) { countMax =计数; keyMax = grp.Key; } } 返回 keyMax; }
干杯
hi
can any one tell, the best way to find a value from an array which is repeated most times
ex
string[] array = new string[] {"1","2","2","3","3","4","2","3","4","4","2","2",};
Expect Ans: 2
解决方案
"Best" in what sense?
There are a huge variety of ways to do this, a few of which are:
1) A foreach loop, counting occurrences into a separate array or Dictionary. Then sort the instances my count, and take the top value.
2) A Linq Query to do the same.
3) Sort the original array, then loop though, counting occurrences and picking the largest as you go.
Which way would I do it? Depends on what the data to check was, and how many of them there were.
"Best" is a subjective word - it can mean "fastest", "smallest", "clearest", "most understandable" or even "least understandable so no-one else will touch it".
Well this is maybe a not the most elegant solution but it does the job:
public string GetMaxElementCount(string[] array) { List<string> list = new List<string>(array); IEnumerable<IGrouping<string, string>> g = list.GroupBy(i => i); int countMax = 0; string keyMax = string.Empty; foreach (IGrouping<string, string> grp in g) { int count = grp.Count(); if (countMax < count) { countMax = count; keyMax = grp.Key; } } return keyMax; }
Cheers
这篇关于从大多数重复的数组中找到值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文