Как получить наиболее распространенное значение в массиве Int? (С#)
Как получить наиболее распространенное значение в массиве Int с помощью С#
например: массив имеет следующие значения: 1, 1, 1, 2
Ans должно быть 1
Ответы
Ответ 1
var query = (from item in array
group item by item into g
orderby g.Count() descending
select new { Item = g.Key, Count = g.Count() }).First();
Только для значения, а не для счета, вы можете сделать
var query = (from item in array
group item by item into g
orderby g.Count() descending
select g.Key).First();
Лямбда-версия на втором:
var query = array.GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
Ответ 2
Некоторые старомодные эффективные петли:
var cnt = new Dictionary<int, int>();
foreach (int value in theArray) {
if (cnt.ContainsKey(value)) {
cnt[value]++;
} else {
cnt.Add(value, 1);
}
}
int mostCommonValue = 0;
int highestCount = 0;
foreach (KeyValuePair<int, int> pair in cnt) {
if (pair.Value > highestCount) {
mostCommonValue = pair.Key;
highestCount = pair.Value;
}
}
Теперь mostCommonValue
содержит наиболее распространенное значение, а highestCount
содержит сколько раз это происходило.
Ответ 3
Возможно, O (n log n), но быстро:
sort the array a[n]
// assuming n > 0
int iBest = -1; // index of first number in most popular subset
int nBest = -1; // popularity of most popular number
// for each subset of numbers
for(int i = 0; i < n; ){
int ii = i; // ii = index of first number in subset
int nn = 0; // nn = count of numbers in subset
// for each number in subset, count it
for (; i < n && a[i]==a[ii]; i++, nn++ ){}
// if the subset has more numbers than the best so far
// remember it as the new best
if (nBest < nn){nBest = nn; iBest = ii;}
}
// print the most popular value and how popular it is
print a[iBest], nBest
Ответ 4
public static int get_occure(int[] a)
{
int[] arr = a;
int c = 1, maxcount = 1, maxvalue = 0;
int result = 0;
for (int i = 0; i < arr.Length; i++)
{
maxvalue = arr[i];
for (int j = 0; j <arr.Length; j++)
{
if (maxvalue == arr[j] && j != i)
{
c++;
if (c > maxcount)
{
maxcount = c;
result = arr[i];
}
}
else
{
c=1;
}
}
}
return result;
}
Ответ 5
Я знаю, что это сообщение устарело, но кто-то спросил меня, обратный этому вопросу сегодня.
Группировка LINQ
sourceArray.GroupBy(value => value).OrderByDescending(group => group.Count()).First().First();
Коллекция тем, похожая на Guffa's:
var counts = new Dictionary<int, int>();
foreach (var i in sourceArray)
{
if (!counts.ContainsKey(i)) { counts.Add(i, 0); }
counts[i]++;
}
return counts.OrderByDescending(kv => kv.Value).First().Key;