我想在数组中找到众数。我知道我需要做嵌套循环来检查每个值并查看数组中元素出现的频率。然后我必须计算第二个元素出现的次数。下面的代码不起作用,有人能帮我吗?
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];
}
}
我想在数组中找到众数。我知道我需要做嵌套循环来检查每个值并查看数组中元素出现的频率。然后我必须计算第二个元素出现的次数。下面的代码不起作用,有人能帮我吗?
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];
}
}
int mode = x.GroupBy(v => v)
.OrderByDescending(g => g.Count())
.First()
.Key;
var groups = x.GroupBy(v => v);
int maxCount = groups.Max(g => g.Count());
int mode = groups.First(g => g.Count() == maxCount).Key;
MaxBy
扩展来进一步改进解决方案,以便仅需要遍历所有元素一次。一种非LINQ的解决方案:
int[] x = new int[] { 1, 2, 1, 2, 4, 3, 2 };
Dictionary<int, int> counts = new Dictionary<int, int>();
foreach( int a in x ) {
if ( counts.ContainsKey(a) )
counts[a] = counts[a]+1
else
counts[a] = 1
}
int result = int.MinValue;
int max = int.MinValue;
foreach (int key in counts.Keys) {
if (counts[key] > max) {
max = counts[key];
result = key;
}
}
Console.WriteLine("The mode is: " + result);
result = key;
应该放在 if 语句的主体内吗? - Mark Byerscounts[a]++;
呢? - Necronomicronx
.GroupBy(i => i) //place all identical values into groups
.OrderByDescending(g => g.Count()) //order groups by the size of the group desc
.Select(g => g.Key) //key of the group is representative of items in the group
.First() //first in the list is the most frequent (modal) value
假设,x数组的项如下:
int[] x = { 1, 2, 6, 2, 3, 8, 2, 2, 3, 4, 5, 6, 4, 4, 4, 5, 39, 4, 5 };
a. 获取最高值:
int high = x.OrderByDescending(n => n).First();
b. 获取模态框:
int mode = x.GroupBy(i => i) //Grouping same items
.OrderByDescending(g => g.Count()) //now getting frequency of a value
.Select(g => g.Key) //selecting key of the group
.FirstOrDefault(); //Finally, taking the most frequent value
FirstOrDefault
会错误地声明数组的模式为 0
。 - user7116
Count()
调用不会遍历IGrouping
来查找计数吗?所以实际上你的最坏情况是O(n^2)? - Adam Goodwin