如何找到二进制数组中最长连续1的开始和结束位置(或)索引
EX:110011110011->起始位置为4,结束位置为7
答案 0 :(得分:-1)
尝试以下代码:
#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
答案 1 :(得分:-1)
您可以尝试这个简单的代码。我假设数组的长度为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;
}
}
}