485. Max Consecutive Ones
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
and1
. - The length of input array is a positive integer and will not exceed 10,000
//参考解
//运用乘法,效率一般
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums)
{
int max = 0;
int numsSize=nums.size();
int sum = 0;
for (int i=0; i<numsSize; i++)
{
sum = (sum+nums[i])*nums[i];
if(max<sum){max=sum;}
}
return max;
}
};
//解1
//分为在0列or1列两种情况
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums)
{
int res=0;
int length=nums.size();
bool flag=0;//标志位
int num=0;//当前列连续1的个数
for(int i=0;i<length ;i++)
{
if(flag)//在1队列中
{
if(nums[i])
{
num++;
res=num>res?num:res;
}
else
{
flag=0;
num=0;
}
}
else//在1队列外
{
if(nums[i])
{
flag=1;
num++;
res=1>res?1:res;
}
}
}
return res;
}
};