Problem:
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.Code:
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int count2 = 0;
for(int i = 0; i < nums.length; i++){
if (nums[i] == 0){
count2 = 0;
}
if (nums[i] == 1){
count2 += 1;
}
count = Math.max(count,count2);
}
return count;
}
}
Code2:
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int count2 = 0;
for(int n : nums){
count = Math.max(count,count2 = n == 0 ? 0 : count2 + 1); //高手倾向于用增强型for循环和三目运算符写
}
return count;
}
}