阵列中的最大连续重复 [英] maximum consecutive repetition in an array

查看:104
本文介绍了阵列中的最大连续重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要计数数组中的最大连续trues。在下面,这回我4.看来,数组中的所有trues相加。这有什么错我的工作?这里是我的code。

  INT的main()
{
INT MAXCOUNT = 0;
布尔列表[7];
列表[0] =真;
清单[1] =真;
清单[2] = FALSE;
清单[3] = FALSE;
清单[4] =真;
清单[5] =真;
清单[6] = FALSE;的for(int i = 0;我6;;我++)
{
    诠释计数= 0;
    如果(名单[I] ==真)
    {
        算上++;
        为(中间体J = + 1; J&下; 7; J ++)
        {
            如果(名单[J] ==名单[I])
            {
                算上++;
            }
        }
    }
    如果(计数> MAXCOUNT)
    {
        MAXCOUNT =计数;
    }
}
COUT<< MAXCOUNT<< ENDL;
}


解决方案

您正在实现的方式是完全错误的。您正将所有的真正项数组中,没有占到一个之间。

做到这一点:

  INT CURRENTCOUNT = 0,MAXCOUNT = 0;
对(INT I = 0; I&7; ++ⅰ)
{
    // ARR是数组名
    如果(ARR [I])++ CURRENTCOUNT;
    否则CURRENTCOUNT = 0; //重新设置到零,如果遇到假
    MAXCOUNT =((CURRENTCOUNT> MAXCOUNT)CURRENTCOUNT:MAXCOUNT);
}
COUT<< MAXCOUNT<< ENDL;

I want to count the maximal consecutive trues in the array. In the follows, it return me 4. It seems that all the trues in the array are added up. What's wrong with my work? Here is my code.

int main()
{
int maxCount = 0;
bool list[7];
list[0] = true;
list[1] = true;
list[2] = false;
list[3] = false;
list[4] = true;
list[5] = true;
list[6] = false;

for (int i = 0; i < 6; i++)
{
    int count = 0;
    if (list[i]==true)
    {
        count++;
        for (int j = i + 1; j < 7; j++)
        {
            if (list[j]== list[i])
            {
                count++;
            }
        }
    }
    if (count > maxCount)
    {
        maxCount = count;
    }
}
cout << maxCount << endl;
}

解决方案

The way you are implementing is completely wrong. You are adding all the true entries in the array, without accounting for a false in between.

Do this:

int currentCount = 0, maxCount = 0;
for (int i = 0; i < 7; ++i)
{
    // arr is the name of the array
    if(arr[i])    ++currentCount;
    else    currentCount = 0;  // resetting to zero if false encountered
    maxCount = ( (currentCount > maxCount) ? currentCount : maxCount );
}
cout << maxCount << endl;

这篇关于阵列中的最大连续重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆