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
- 题目的意思就是给定一个只有0和1的数组,并且假定这个数组的的长度是一个不超过10000的正整数,要求最长的1的个数
题目比较简单就直接贴代码了
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
//一个计数器记录1的个数
int k = 0;
//表示最大的1的个数
int max = 0;
for(int i=0;i<nums.length;i++){
if(nums[i]==1){
k++;
if(k>max)
max = k;
}
else
//如果出现了0,就将k置0重新计数
k = 0;
}
return max;
}
}