题目描述:
Given a binary array, find the maximum number of consecutive 1s in this array.
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
思路一:
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int max = 0;
int tmpMax = 0;
for (int i = 0; i < nums.length; i++)
{
if (nums[i] == 1 && i != nums.length - 1)
tmpMax++;
else if (nums[i] == 1 && i == nums.length - 1)
{
tmpMax++;
max = (tmpMax > max) ? tmpMax : max;
}
else if (nums[i] == 0 && tmpMax != 0)
{
max = (tmpMax > max) ? tmpMax : max;
tmpMax = 0;
}
}
return max;
}
}
思路二:
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int max = 0;
int tmpMax = 0;
for (int num : nums)
{
max = Math.max(max, tmpMax = (num == 0 ? 0 : tmpMax + 1));
}
return max;
}
}