c# - 程序如何知道数组达到 10?
问题描述
我对这个任务有疑问:
编写一个 C# 程序,该程序将接受整数列表并检查需要多少整数才能完成该范围。例如 [1, 3, 4, 7, 9],在 1-9 -> 2, 5, 6, 8 之间不存在于列表中。所以输出将是4。
这是该任务的代码:
public class Example
{
public static int consecutive_array(int[] input_Array)
{
Array.Sort(input_Array);
int ctr = 0;
for (int i = 0; i < input_Array.Length - 1; i++)
{
ctr += input_Array[i + 1] - input_Array[i] - 1;
}
return ctr;
}
public static void Main()
{
Console.WriteLine(consecutive_array(new int[] { 1, 3, 5, 6, 9 }));
Console.WriteLine(consecutive_array(new int[] { 0, 10 }));
Console.ReadLine();
}
}
我的问题是,程序如何知道数组从 0 变为 9。我们只定义了数组的长度。
解决方案
目前尚不清楚您的问题是什么。既然你完成了作业,你应该至少了解代码是如何工作的。如果您没有编写代码,那么也许您应该询问您复制它的人。如果这不是一个选项,则单步执行/调试代码。
为了解决这个问题,我会略有不同:
您知道长度应该是最大值和最小值之间的差,并且您知道长度是多长,所以这应该是简单的算术算法来确定长度input_Array
和长度之间的差,如果它是依次满:
public static int consecutive_array(int[] input_Array)
{
// we know the array length SHOULD be ==( max - min + 1)
Array.Sort(input_Array);
int fullLength = (input_Array[input_Array.Count()-1] - input_Array[0] + 1);
return (fullLength - input_Array.Length);
}
推荐阅读
- google-sheets-formula - ARRAYFORMULA 对所有列进行递归求和列
- android - Can i install different google play tracks on the same device at the same time?
- python - 用于检测重复记录的工具或 python 库
- java - xiaomi android 7:JobIntentService.onHandleWork() 循环运行
- javascript - 如何让这个秒表在停止启动后继续运行,而不是在停止启动时重置为 00:00:00?
- python - 当参数等于 1 时,Lambda if else 语句返回 True
- javascript - Vue如何添加电话号码通话链接
- c# - C# WPF OnDragMoveWindow 只需单击即可执行?
- python - 绘制从 Pandas 到 Seaborn 的多条线图
- flutter - Flutter Firestore await .getDocuments 花了 30 分钟