编程找到数组中出现最大值的元素并按降序对数组进行排序? [英] Program to find the element which has maximum occurence in an array and sort the array in descending order?
问题描述
我有一个数组如
ar [] = {5,7 ,3,5,3,6,5,2,1}
在此我要打印出现次数最多的数字
o / p = 5(因为它在阵列中发生了3次)
并且还按降序排序
1,2,3,5,6,7
提前致谢
< blockquote>这实际上应该有效,
var max = ar.GroupBy(x = > x).MaxBy(x = > x.Count())。First()。Key;
和降序,
var max = ar.GroupBy(x = > x).OrderByDescending(x = > x.Count( ))。第一个()。键;
如果它不起作用,请告诉我。 :)
见这个链接 [ ^ ]。
-KR
int [] array = { 5 ,< span class =code-digit> 7 , 3 , 5 , 3 , 6 , 5 , 2 , 1 };
先按升序排序,然后按反向数组排序
Array.Sort(array);
Array.Reverse(array);
foreach ( var item in array){Console.Write(item); }
要查找哪个号码有最大出现次数,请尝试:
var numOccurrencies = new Dictionary< int,int>();
int numberWithMaxOccurrencies = 0 ;
int maxOccurrences = 0 ;
foreach ( var item in 数组)
{
if (!numOccurrencies.ContainsKey(item))
{
numOccurrencies.Add(item , 0 );
}
numOccurrencies [item] ++;
if (numOccurrencies [item] > maxOccurrences)
{
numberWithMaxOccurrencies = item;
maxOccurrences = numOccurrencies [item];
}
}
Console.WriteLine( 数字{0}有{1 } occurrencies。,numberWithMaxOccurrencies,maxOccurrences);
Hi ,
I have an array like
ar[]={5,7,3,5,3,6,5,2,1}
in this i want to print the number which has maximum occurrence
o/p=5 (because it has occurred 3 times in array)
and also do the sorting in descending order
1,2,3,5,6,7
Thanks in advance
This should work actually,
var max = ar.GroupBy(x => x).MaxBy(x => x.Count()).First().Key;
and for Descending order,
var max = ar.GroupBy(x => x).OrderByDescending(x => x.Count()).First().Key;
Let me know if it is not working. :)
See this link[^] as well.
-KR
int[] array = { 5, 7, 3, 5, 3, 6, 5, 2, 1 };
Sort by ascending first, then reverse array
Array.Sort(array); Array.Reverse(array); foreach (var item in array) { Console.Write(item); }
To find which number has max occurencies try this:
var numOccurrencies = new Dictionary<int, int>(); int numberWithMaxOccurrencies = 0; int maxOccurrences = 0; foreach (var item in array) { if (!numOccurrencies.ContainsKey(item)) { numOccurrencies.Add(item, 0); } numOccurrencies[item]++; if (numOccurrencies[item] > maxOccurrences) { numberWithMaxOccurrencies = item; maxOccurrences = numOccurrencies[item]; } } Console.WriteLine("Number {0} has {1} occurrencies.", numberWithMaxOccurrencies, maxOccurrences);
这篇关于编程找到数组中出现最大值的元素并按降序对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!