[英]How to find the beginning and ending indices of groups of ones in a set of ones and zeros
我將如何找到一組的開始和結束索引。 我嘗試了一些復雜的嵌套 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,重復
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.