您的位置:首页 > 其它

[leetcode]: 485. Max Consecutive Ones

2017-05-01 18:14 369 查看
1.题目描述

Given a binary array, find the maximum number of consecutive 1s in this array.

给一个0-1数组,找出最长的连续1的个数

例:

Input: [1,1,0,1,1,1]

Output: 3

2.分析

从左到右遍历数组,对连续的1计数,遇到0则重新开始计数,并更新计数最大值。

3.代码

c++

int findMaxConsecutiveOnes(vector<int>& nums) {
int count = 0;
int maxC = 0;
for (int n : nums) {
if (n == 1)//连续的1,计数
count++;
else if (n == 0 && count > 0) {//出现0,打破连续
if (count > maxC)//更新最大连续长度
maxC = count;
count = 0;//计数重置为0
}
}
if (count > maxC)//遍历结束,更新最大连续长度
maxC = count;
return maxC;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode