gpt4 book ai didi

c# - 按顺序搜索缺失的数字

转载 作者:太空宇宙 更新时间:2023-11-03 18:54:51 25 4
gpt4 key购买 nike

假设我有以下数组(我的序列都是按升序排列的,并且包含正整数)

var tabSequence = new[] { 1, 2, 3, 7, 8, 9, 12, 15, 16, 17, 22, 23, 32 };

我使用 LINQ 和循环编写了一个代码来搜索丢失的数字:

List<Int32> lstSearch = new List<int>();
var lstGroup = tabSequence
.Select((val, ind) => new { val, group = val - ind })
.GroupBy(v => v.group, v => v.val)
.Select(group => new{ GroupNumber = group.Key, Min = group.Min(), Max = group.Max() }).ToList();

for (int number = 0; number < lstGroup.Count; number++)
{
if (number < lstGroup.Count-1)
{
for (int missingNumber = lstGroup[number].Max+1; missingNumber < lstGroup[number+1].Min; missingNumber++)
lstSearch.Add(missingNumber);
}
}
var tabSequence2 = lstSearch.ToArray();
// Same result as var tabSequence2 = new[] {4, 5, 6, 10, 11, 13, 14, 18, 19, 20, 21, 24, 25, 26, 27, 28, 29, 30, 31 };

此代码有效,但我想知道是否有更好的方法仅使用 linq 来完成同样的事情。

最佳答案

也许我只是不明白这个问题。你的代码看起来很复杂,你可以让它变得更简单:

int[] tabSequence = new[] { 1, 2, 3, 7, 8, 9, 12, 15, 16, 17, 22, 23, 32 };

var results = Enumerable.Range(1, tabSequence.Max()).Except(tabSequence);

//results is: 4, 5, 6, 10, 11, 13, 14, 18, 19, 20, 21, 24, 25, 26, 27, 28, 29, 30, 31

我做了一个 fiddle here

关于c# - 按顺序搜索缺失的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48191841/

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