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;
}
}
本文介绍了一种通过遍历数组并记录连续1的数量来找出最长连续1序列的方法。使用两个计数变量,一个用于记录当前连续1的数量,另一个用于记录迄今为止遇到的最长连续1序列的长度。

1351

被折叠的 条评论
为什么被折叠?



