c# - 用于查找数组中重复次数最多的 C# 函数
问题描述
您好我正在尝试为一个函数编写一个 C# (Visual Studio) 程序,该函数在数组中接受整数,并返回一个整数数组,其中包含输入数组中最常见的整数。
样品输入输出 -
[1,2,3,4,3,3,2,2,4] result = [2,3]
[1, 2, 3, 4, 5, 1, 6, 7, 1, 1] result = [1]
[1, 2, 3, 4, 5, 6, 7] result = [1, 2, 3, 4, 5, 6, 7]
我快到了,但没有得到预期的结果。以下是我编写的代码,我是初学者。
namespace StringCommonElements
{
class Program
{
static void Main(string[] args)
{
// Compute frequencies for this data.
string[] values = { "bird", "cat", "bird", "dog", "bird", "man", "frog", "cat" };
// Get a list.
List<string> valuesList = new List<string>(values);
// Call our methods.
var freqs = GetFrequencies(valuesList);
DisplaySortedFrequencies(freqs);
}
static Dictionary<string, int> GetFrequencies(List<string> values)
{
var result = new Dictionary<string, int>();
foreach (string value in values)
{
if (result.TryGetValue(value, out int count))
{
// Increase existing value.
result[value] = count + 1;
}
else
{
// New value, set to 1.
result.Add(value, 1);
}
}
// Return the dictionary.
return result;
}
static void DisplaySortedFrequencies(Dictionary<string, int> frequencies)
{
// Order pairs in dictionary from high to low frequency.
var sorted = from pair in frequencies
orderby pair.Value descending
select pair;
// Display all results in order.
foreach (var pair in sorted)
{
Console.WriteLine($"{pair.Key} = {pair.Value}");
}
}
}
}
解决方案
这是使用 Linq 执行此操作的方法。这将对数字进行分组并找到每个数字的计数,然后取出所有出现多次的数字。然后,如果结果为空,则返回原始数组,因为所有数字都是唯一的。
public int[] MostCommon(int[] numbers)
{
var ans = numbers
.GroupBy(x => x)
.Select(x => new {x.Key, x.Count}))
.Where(x => x.Count > 1)
.Select(x => x.Key)
.ToArray();
return ans.Length > 0 ? ans : numbers;
}
推荐阅读
- powerbi - 如何使用 DAX 查找具有相同 ID 的 2 个或多个元素的值之间的差异
- visual-studio-code - 在 vs 代码中包装多行注释
- javascript - JQuery preventDefault 不会停止页面重新加载
- python - 近似小于或等于的可微张量运算?
- algorithm - 有没有办法在分区的 spark 数据集上并行运行操作?
- tensorflow-estimator - 如何将 RMSE 添加到预制估计器中
- python - Opencv:仅在捕获图像时才由零组成的 Numpy 数组
- mongodb - 如何修复 mongo 中的 SSL 错误“CSSMERR_TP_VERIFY_ACTION_FAILED”?
- loops - 如何遍历包含多个数字的行的文本文件,同时计算数字
- r - R,在循环中添加数据帧