Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:
Input: [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
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的个数。
思路:遍历数组,用一个计数器tmp来统计1的个数,如果当前数字为0,那么tmp重置为0,如果是1,tmp自增1,然后每次更新结果max。
public class Solution { public int findMaxConsecutiveOnes(int[] nums) { if(nums==null) return 0; int max=0; int tmp=0; for(int i=0;i<nums.length;i++){ if(nums[i]==0) { tmp=0; }else{ tmp++; if(tmp>max) max=tmp; } } return max; } }