二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位

Maximum consecutive one’s starting and ending index in a binary array in C++

本文关键字:索引 结束 为单位 C++ 数组 连续 二进制      更新时间:2023-10-16

如何找到二进制数组中最长的连续 1 的起始和结束位置(或(索引

例如:110011110011 -> 起始位置为 4,结束位置为 7

试试这段代码:

#include<iostream>
#include<string>
using namespace std;
int main(){
int longest = 0;
int stpos = 0;
int lpos = 0;
string s = "110011110011";
for(int i=0; i<s.length();){
char current = s[i];
int currLen = 0;
for(;i<s.length() && current == s[i]; ++i){
++currLen;
stpos = i;}
if(currLen > longest){
longest = currLen ;
lpos = stpos;}
}
cout<<"longest streak length:"<<longest<<endl;;
cout<<"starting index:"<<lpos-longest+1<<endl;
cout<<"ending index:"<<lpos<<endl;;
return 0;
}

输出为:

longest streak length:4
starting index:4
ending index:7

你可以试试这个简单的代码。我假设数组的长度为 12。

int arr[12];
int lower=0;
int upper=0;
int max_count=0;
int count=0;
for(int i=0;i<12;i++)
{   
if(arr[i]==1)
{
count++;
}
else
{
if(max_count<count)
{
lower=i-count;
max_count=count;
upper=i-1;
count=0;
}
}
}