题目
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;
}
};

本文介绍了一种寻找给定二进制数组中最长连续1序列的方法。通过遍历数组并使用计数器跟踪连续1的数量,该算法能高效地找到最长序列。注:数组只包含0和1,且长度不超过10000。
1282

被折叠的 条评论
为什么被折叠?



