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的數(shù)組括改,并且假定這個數(shù)組的的長度是一個不超過10000的正整數(shù)壮池,要求最長的1的個數(shù)
題目比較簡單就直接貼代碼了
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
//一個計數(shù)器記錄1的個數(shù)
int k = 0;
//表示最大的1的個數(shù)
int max = 0;
for(int i=0;i<nums.length;i++){
if(nums[i]==1){
k++;
if(k>max)
max = k;
}
else
//如果出現(xiàn)了0十酣,就將k置0重新計數(shù)
k = 0;
}
return max;
}
}