gpt4 book ai didi

c# - 查找重复多次的重复数字 C#

转载 作者:太空狗 更新时间:2023-10-29 20:07:00 29 4
gpt4 key购买 nike

我们如何在 int 数组中找到重复次数超过两次的重复数字。我的例子之一如下

public static void main()
{
int[] array = { 3, 7, 9 , 7, 4, 9, 7 , 9}
Dictionary<int,int> dic = new Dictionary<int,int>();
foreach(var Val in array)
{
if(dict.containskey(Val)
dic[Val] ++;
else
dic[Val] = 1 ;
}

foreach (var pair in dic)
if(key.value > 2 )
Console.WriteLine(pair.key)
}

有没有更好的方法来做到这一点?我在一次采访中被问到。我给出了被拒绝的上述解决方案。

编辑::我被要求编写一个占用更少内存且性能良好的程序。它不应该使用 linq 或任何内置的 C# 扩展方法......

最佳答案

将您的项目分组并仅取出现次数超过 2 次的项目:

array.GroupBy(x=>x).Where(x=>x.Count()>2).Select(x=>x.Key)

关于c# - 查找重复多次的重复数字 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41518802/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com