// Source : https://leetcode-cn.com/problems/max-consecutive-ones/
// Date : 2021-10-9
题目描述:
给定一个二进制数组, 计算其中最大连续 1 的个数。
示例:
输入:[1,1,0,1,1,1]
输出:3
解释:开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3.
提示:
输入的数组只包含 0 和 1 。
输入数组的长度是正整数,且不超过 10,000
题目分析: 首先设置最大值和计数器,当数组中出现1的时候就把计数器自增,如果出现0,就把计数器归零,以便下次出现1的时候可以重新自增,每次自增结束以后判断现在的计数器和最大值的大小,如果现在的计数器大于最大值,则需要更新最大值,最终遍历结束,将最大值返回即可。
代码:
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums)
{
int max = 0;
int count = 0;
for (int i = 0; i < nums.size(); i++)
{
//如果数据为1,就将计数器自增
if (nums[i] == 1)
{
count++;
//如果计数器大于max,就更新
if (count > max)
max = count;
}
//如果数据不是1,就把count归零
else
count = 0;
}
return max;
}
};