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 and 1.
The length of input array is a positive integer and will not exceed 10,000
给一个二进制数组,在这个数组中找出连续为1的最大次数。
直接上代码吧
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int n = 0;//最大连续的零数
int t = 0;//1连续的次数
for (int i = 0; i < nums.size(); i++)
{
if (nums[i])//每当遇到1时
{
t++;//计数加一
if (t > n)
{
n = t;//保证每次n都代表最多的1数
}
}
else
{
t = 0;//否则t一直是0
}
}
return n;
}
};