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.
思路:
1,求数组的和
2,若和为0,则不存在1,返回0
3,若和为1,则只有一个1,返回1
4,有两个或两个以上的1,则设置一个两个变量,分别表示每段连续的1的长度和最长的长度
#pragma once
#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
//求和
int sum = accumulate(nums.begin(), nums.end(),0);
//若和为0,则没有1
if (sum == 0)
{
return 0;
}
//如果和为1,则只有一个1
if (sum == 1)
{
return 1;
}
//否则有两个及以上的1,则判断是否连续
int leng = nums.size();
int one = 0;//1的个数
int onesum = 0;//1的最长序列的个数
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == 1)
{
//如果是1,则计数
one += 1;
if (one > onesum)
{
onesum = one;
}
}
else
{
one = 0;
}
}
return onesum;
}
};