c# - 使用 C# 查找示例模式
问题描述
我有这样一个样本:[5,3,5,5,8,9,8,8,6,1]
我想找到模式。在这种情况下 5 和 8。
我已经实现了这样的方法:
static List<int> Mode(int[] array)
{
if (array.Length == 0)
{
throw new ArgumentException("Sample can't be empty");
}
List<int> result = new List<int>();
var counts = new Dictionary<int, int>();
int max = 0;
foreach (int num in array)
{
if (counts.ContainsKey(num))
counts[num] = counts[num] + 1;
else
counts[num] = 1;
}
foreach (var key in counts.Keys)
{
if (counts[key] > max)
{
max = counts[key];
result.Add(max);
}
}
return result;
}
但是输出是1,3
怎么了?
解决方案
您添加Dictionary 的值,counts
它们是初始数组中相同数字的数量:
foreach (var key in counts.Keys)
{
if (counts[key] > max)
{
max = counts[key];
result.Add(max);
}
}
您可能想要添加keys
以查看哪些数字有重复:
// int max = 0; <-- not needed
foreach (var key in counts.Keys)
{
// Check that number from initial array (key)
// have duplicates (value is more than 1)
if (counts[key] > 1)
{
// Add to result not amount of duplicates (value),
// but number (key) which has duplicates
result.Add(key);
}
}
它将为您提供[5,3,5,5,8,9,8,8,6,1]数组中的5和8 。
推荐阅读
- html - 2 列布局,具有 1 个纵横比容器和一个全高 div
- liferay - Liferay 7.0 获取通过组继承的角色
- c - 为什么即使设置了 SA_NODEFER 标志,sigaction 处理程序也不处理每个信号?
- ios - 使用 iOS 图表在条形图中的 X 轴标签上添加属性文本
- javascript - 根据另一个对象数组的顺序对对象数组进行排序
- r - 有条件地创建单个变量
- php - 无法从 laravel 中的 AJAX 调用中获取 responseText
- javascript - 我怎样才能从非子组件访问主要组件?反应
- php - PHP 错误日志级别控制:htaccess vs php.ini vs code 和 virtualhost
- python - 是否有可能知道它在哪个选项卡中打开(“window.open('_blank');”在 Selenium 中?