Description:
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),找出连续1的最长长度;
解法:我们只需要遍历一遍数组,记录局部的最长长度,同时记录一个全局最长长度,返回两者较长的那个;
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int max = 0;
int currentMax = 0;
for(int num : nums) {
currentMax = num == 1 ? currentMax + 1 : 0;
max = currentMax > max ? currentMax : max;
}
return max;
}
}