您的位置:首页 > 编程语言 > C语言/C++

LeetCode -485. Max Consecutive Ones - 思路详解 - C++

2017-01-15 21:59 429 查看

题目

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

Note:

The input array will only contain 0 and 1.

The length of input array is a positive integer and will not exceed 10,000

翻译

假设有个一数组,找出数组中最长连续的1的序列。

注:

1,数组中值仅包含0和1

2,输入数组长度为正整数,且不会超过10000

思路

遍历数组,如果是1,则计数加一,如果是0,则将当前计数值和最大值比较更新。然后计数计数清零。

代码

class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int len = nums.size();
int max = 0;
int cnt = 0;
for(int i = 0; i < len;i++){
if(nums[i] != 0){
cnt++;
}else{
if(cnt > max){
max = cnt;
}
cnt = 0;
}
}

if(cnt > max){
max = cnt;
}
return max;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: