问题描述:Given a binary array, find the maximum number of consecutive 1s in this array.
即 找到二进制数组中最多的连续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
and1
. - The length of input array is a positive integer and will not exceed 10,000
原理流程见图片
根据流程图,代码很简单就可以得出:
public class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int n=0,n1=0;
for(int x=0;x<nums.length;x++)
{
if (nums[x]==1)
{
n1++;
}
else if(nums[x]==0)
{
if(n1>n)
{
n=n1;
n1=0;
}
else n1=0;
}
}
return n>n1?n:n1;
}
}
return采用三元运算表达式简化结果。