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

C#遍历数组统计连续重复元素时循环无法输出末尾重复值问题求助

问题原因
  • 末尾连续重复序列的拼接逻辑存在遗漏:遍历到数组最后一位且和前一位相等时,仅把array[i-1]加入拼接字符串,漏掉了最后一位array[i],同时拼接时没有留空格,会导致重复元素和计数直接粘连
  • 循环结束后的兜底入库逻辑没有过滤重复次数为1的情况:如果数组末尾是单个不重复元素,会错误地把无效的非重复序列写入结果集
  • 冗余的(i + 1) != array.Length判断拆分了重复序列的拼接逻辑,既增加了代码复杂度,也提升了出错概率
修复后代码
List<string> duplicateArrays = new List<string>();
// 数组长度不足2不可能存在连续重复元素,直接返回
if (array.Length < 2)
{
    return;
}
int duplicateCount = 1;
string duplicate = "";

for (int i = 1; i < array.Length; i++)
{
    if (array[i - 1] == array[i])
    {
        duplicateCount++;
        duplicate += array[i - 1] + " ";
    }
    else
    {
        // 仅统计连续重复次数≥2的序列
        if (duplicateCount >= 2)
        {
            // 补上当前段最后一个重复元素,再拼接次数
            duplicate += array[i - 1] + " " + duplicateCount;
            duplicateArrays.Add(duplicate);
        }
        // 重置状态进入下一段统计
        duplicate = "";
        duplicateCount = 1;
    }
}

// 单独处理数组末尾的剩余重复序列
if (duplicateCount >= 2)
{
    duplicate += array[array.Length - 1] + " " + duplicateCount;
    duplicateArrays.Add(duplicate);
}
验证说明

你给出的示例数组{3,3,3,3,4}运行后会正确输出3 3 3 3 4;如果数组末尾是连续重复元素,比如{1,2,2,2},也会正确输出2 2 2 3,不会出现遗漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:24:03