You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

移除列表中连续数字对的C#代码异常排查

问题描述

需要移除整数列表中的连续数字对(即仅由两个连续数组成的序列,比如11,12、14,15、26,27这种长度为2的连续序列要移除;而长度≥3的连续序列如1,2,3,4,5、7,8,9则保留)。

输入列表:

{ 1, 2, 3, 4, 5, 100, 11, 12, 100, 14, 15, 100, 7, 8, 9, 100, 26, 27 }

预期输出:

{ 1, 2, 3, 4, 5, 100, 100, 100, 7, 8, 9, 100 }

原执行代码:

var list = new List<int> { 1, 2, 3, 4, 5, 100, 11, 12, 100, 14, 15, 100, 7, 8, 9, 100, 26, 27 };

list.Add(-1);
int counter = 0;
bool nonecons = false;

for (int i = 0; i < list.Count; i++)
{
    if ((i + 1 < list.Count))
    {
        if ((list[i + 1] - list[i]) == 1)
        {
            counter++;
        }
        else
        {
            nonecons = true;
            if (counter < 2 && nonecons == true) 
            {
                if (list[i] != 100)
                {
                    list.Remove(list[i]);
                    list.Remove(list[i - 1]);
                }

                counter = 0;
                nonecons = false;
            }
            else if (counter >= 2 && nonecons == true) 
            {
                counter = 0;
                nonecons = false;
            }
        }
    }
}
list.RemoveAt(list.Count - 1);

运行后意外结果:

{ 1, 2, 3, 4, 5, 100, 100, 100, 7, 100 }
问题分析与修改方案

原代码的核心问题有两个:

  • 遍历中直接修改List导致索引混乱:Remove操作会改变列表长度和元素位置,后续的索引i不会自动调整,导致跳过元素或误删。比如处理7,8,9时,错误的索引逻辑会误删8,9。
  • 连续序列的判断逻辑模糊:counter的统计和判断逻辑没有清晰区分“长度为2的连续序列”和“长度≥3的连续序列”。

推荐改用新建列表收集保留元素的方式,逻辑更清晰且不会出现索引问题:

修改后的代码:

var list = new List<int> { 1, 2, 3, 4, 5, 100, 11, 12, 100, 14, 15, 100, 7, 8, 9, 100, 26, 27 };
var result = new List<int>();
int i = 0;

while (i < list.Count)
{
    // 检查当前位置是否开始一段连续序列
    if (i + 1 < list.Count && list[i + 1] - list[i] == 1)
    {
        int start = i;
        // 找到连续序列的结束位置
        while (i + 1 < list.Count && list[i + 1] - list[i] == 1)
        {
            i++;
        }
        // 连续序列长度≥3则保留所有元素,否则跳过(移除这对)
        if (i - start + 1 >= 3)
        {
            result.AddRange(list.GetRange(start, i - start + 1));
        }
    }
    else
    {
        // 非连续元素直接保留
        result.Add(list[i]);
    }
    i++;
}

// 输出结果(可选)
foreach (var num in result)
{
    Console.Write(num + " ");
}

代码说明

  • 用while循环遍历,方便控制索引位置,避免遍历中修改原列表的问题。
  • 先定位连续序列的起止位置,计算序列长度:
    • 长度≥3:将整个序列加入结果列表。
    • 长度=2:直接跳过,不加入结果(即移除这对连续数)。
  • 非连续的单个元素(比如100)直接加入结果列表。

运行这段代码后,就能得到符合预期的输出:1 2 3 4 5 100 100 100 7 8 9 100

内容的提问来源于stack exchange,提问作者blacksunday

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 02:40:37