二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
Maximum consecutive one’s starting and ending index in a binary array in C++
如何找到二进制数组中最长的连续 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;
}
}
}
相关文章:
- 数组索引的值没有增加
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 为什么在这个代码结束循环中没有得到结束
- 查找最接近的大于当前数字的数字的索引
- 在C++中调整向量中的索引
- 重载元组索引运算符-C++
- 试图对缓存进行跨步测试,但程序并没有结束
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 为std::string的某个索引赋值
- 并行用于C++17中数组索引范围内的循环
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 跟随整数索引列表的自定义类迭代器
- 如何在for循环中包含两个索引值的测试条件
- 二进制数组中最大连续 1 的起始和结束索引,以 C++ 为单位
- 错误:"结束索引"中没有名为"rank_"的成员
- 返回二维矢量的结束索引
- 如何将排序的元素从数组中的起始索引获取到结束索引
- 从char数组中获取从起始索引到结束的字符串
- 开始和结束数组索引算法
- Boost.MultiArray 任意开始和结束索引