如何在一组1和0中找到一组的起始和结束指标

How to find the beginning and ending indices of groups of ones in a set of ones and zeros

本文关键字:一组 结束      更新时间:2023-10-16

如何找到一组的起始和结束索引?我尝试了一些复杂的嵌套if语句,但没有成功。有没有一个算法来处理这类问题,或者它有一个名字。谢谢。

int arr[32] = {0,1,1,1,1,0,0,0,
             1,1,1,0,0,0,0,0,
             1,1,0,1,0,0,0,1,
             0,0,0,0,0,1,1,1};

我怀疑这个算法是否有特定的名称,但这里有一个变体要考虑:

int i = 0;
while (i < 32) {
    while (i < 32 && arr[i] == 0) i++;
    if (i < 32) {
        cout << "Found start index " << i << endl;
        while (i < 32 && arr[i] == 1) i++;
        cout << "Found end index " << (i - 1) << endl;
    }
}
// of course move 32 to local variable outside the loop

的主要思想:跳过所有的0,如果我们还没有到达数组的末尾-找到所有的1,重复