题目:给定一个二进制数组 nums
, 计算其中最大连续 1
的个数。
方法一:
思路:创建变量count记录连续1的个数,在创建变量max记录最大连续1的个数,遍历数组,当遇到1时+1即可,当遇到0的时候,将其个数还原为0。
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int max = 0;
int count = 0;
for(int val : nums)
{
if(val == 1)
count++;
else
count = 0;
max = max > count ? max : count;
}
return max;
}
}
方法二:
利用快慢指针,slow,fast,如果该元素为1,将fast向后走一步,如果为0将fast向后走一步,并且将slow移到fast所在的位置,每次fast与slow之间的元素个数就是连续1个数,保留最大的即可
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int left = 0;
int right = 0;
while(right < nums.length)
{
if(nums[right] == 1)
right++;
else
{
right++;
left = right;
}
count = count > (right - left) ? count : (right - left);
}
return count;
}
}