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

如何在随机生成的数组中查找连续重复的数字(2个及以上连续)

解决连续重复数字的统计问题

首先,咱们先梳理下你原代码里的两个核心问题:

  1. 数组越界风险:当循环到i = velikostPolja - 1(数组最后一个元素)时,a[i+1]会访问数组外的内存,这会导致未定义行为,程序可能崩溃或输出错误结果。
  2. 仅能统计相邻重复对:连续3个相同的数字(比如[5,5,5])会被统计两次,但如果想识别连续3个、4个甚至更长的重复段,这个逻辑完全满足不了需求。

下面给你两种针对性的解决方案,适配不同的统计需求:

方案一:统计不同长度的连续重复段数量

这个方案会帮你统计“连续2个相同数字的段有多少个”“连续3个的有多少个”,以此类推——每个连续重复的段只算一次(比如[5,5,5]算1个连续3个的段,而非2次连续2个)。

修复后的完整代码如下:

#include "stdafx.h"
#include <iostream>
#include <ctime>
using namespace std;

int main() {
    srand(time(NULL));
    const int velikostPolja = 100;
    int a[velikostPolja];
    
    // 生成并打印随机数组(加空格更易读)
    for (int i = 0; i < velikostPolja; i++) {
        a[i] = rand() % 10;
        cout << a[i] << " ";
    }
    cout << endl;

    // counts[L] 存储长度为L的连续重复段的数量
    int counts[velikostPolja + 1] = {0};
    int currentLength = 1;

    // 从第二个元素开始遍历,和前一个元素比较
    for (int i = 1; i < velikostPolja; i++) {
        if (a[i] == a[i-1]) {
            currentLength++;
        } else {
            // 遇到不同数字,处理当前连续段
            if (currentLength >= 2) {
                counts[currentLength]++;
            }
            currentLength = 1;
        }
    }
    // 处理数组末尾的最后一个连续段
    if (currentLength >= 2) {
        counts[currentLength]++;
    }

    // 输出统计结果
    cout << "\n连续重复段统计:" << endl;
    for (int L = 2; L <= velikostPolja; L++) {
        if (counts[L] > 0) {
            cout << "连续" << L << "个相同数字的段数:" << counts[L] << endl;
        }
    }

    // 兼容原需求:统计相邻两个连续重复的总次数(连续3个会算2次)
    int totalAdjacentDuplicates = 0;
    for (int L = 2; L <= velikostPolja; L++) {
        totalAdjacentDuplicates += counts[L] * (L - 1);
    }
    cout << "\n相邻两个连续重复的总次数:" << totalAdjacentDuplicates << endl;

    system("pause");
    return 0;
}

代码逻辑说明:

  • 用currentLength跟踪当前连续重复的数字长度,初始值为1(单个元素自身长度为1)。
  • 遍历数组时,若当前元素和前一个相等,就增加currentLength;若不等,就检查当前长度是否≥2,若是则更新对应长度的计数,然后重置currentLength。
  • 遍历结束后必须处理最后一个连续段(因为循环结束时可能还有未统计的重复段)。
  • 通过(L-1)计算每个长度为L的段包含多少个相邻重复对,完美兼容你原代码的统计需求。

方案二:打印所有连续重复段的详细信息

如果你想知道具体哪些数字在哪个位置连续重复了多少次,可以在方案一的统计结果后添加这段代码:

// 打印所有连续重复段的细节
cout << "\n所有连续重复段详情:" << endl;
currentLength = 1;
for (int i = 1; i < velikostPolja; i++) {
    if (a[i] == a[i-1]) {
        currentLength++;
    } else {
        if (currentLength >= 2) {
            cout << "数字" << a[i-1] << "从索引" << (i - currentLength) << "到" << (i-1) << "连续出现" << currentLength << "次" << endl;
        }
        currentLength = 1;
    }
}
// 处理最后一个段
if (currentLength >= 2) {
    cout << "数字" << a[velikostPolja - 1] << "从索引" << (velikostPolja - currentLength) << "到" << (velikostPolja -1) << "连续出现" << currentLength << "次" << endl;
}

这样你就能清晰看到每个重复段的起始、结束索引,以及重复的数字和次数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:08:26