题目描述:给定一个二进制数组, 计算其中最大连续 1 的个数。

image.png
解题思路:
我们通过计数器计数 连续 1 的个数,当 nums[i] == 1 时,count++,nums[i] 为 0 时,则先保存最大 count,再将 count 清零,因为我们需要的是连续的 1 的个数,所以需要清零。

解:

class Solution {

public int findMaxConsecutiveOnes(int[] nums) {

if(nums==null || nums.length==0){

return 0;

}

int result=0;

int count=0;

for(int i=0;i<nums.length;i++){

if(nums[i]==1){

count++;

}else{

result=Math.max(result,count);

count=0;

}

}

return Math.max(result,count);//最后一组连续1计数完成时,count不会清零,所以要做一次比较,返回最大值

}

}