C#查找缺失元素前最大连续序列值报索引越界的解决方法
问题描述
需求为查找数值序列中缺失元素前的最大连续序号:
- 示例输入:整数集合
[1,2,3,6,7,8] - 预期输出:
3
原有C#实现运行时抛出索引越界异常:Index was out of range. Must be non-negative and less than the size of the collection.,需要排查错误并给出正确实现。
原有错误代码
public static void Main() { List<int> nums = new List<int>(){1,2,3,6,7,8}; int count = nums.Count; for(int i=0;i<count;i++){ if((nums[i+1]-nums[i])>1){ Console.WriteLine("Missed Element after digit :" [i]); } } }
错误原因排查
- 循环边界设置错误:循环终止条件为
i < count,当i等于集合最后一个元素的索引count-1时,访问nums[i+1]会超出集合的索引范围,直接触发越界异常。 - 输出语句语法错误:
"Missed Element after digit :" [i]属于非法写法,会尝试读取字符串的第i位字符,既不符合语法逻辑,也无法输出目标结果。 - 核心逻辑缺失:代码仅做了相邻差值判断,没有记录、返回符合需求的连续序号结果。
修正后可运行代码
public static void Main() { List<int> nums = new List<int>(){1,2,3,6,7,8}; int count = nums.Count; // 若序列无任何缺失,默认返回最后一个元素的值 int maxConsecutiveNum = nums[^1]; // 修正循环边界,仅遍历到倒数第二个元素,避免索引越界 for(int i = 0; i < count - 1; i++) { // 找到相邻差值大于1的缺口 if(nums[i+1] - nums[i] > 1) { maxConsecutiveNum = nums[i]; break; } } Console.WriteLine(maxConsecutiveNum); }
- 上述代码运行输出结果为
3,符合预期。
内容的提问来源于stack exchange,提问作者Software Engineer
相关产品推荐
相关产品推荐

