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
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
题解:
此题是给定一个只含二进制0和1的数组,找出数组内最长的连续的1的长度。
首先应当用一个变量记录在遍历数组时遇到的连续的1的长度,再用另一个变量更新目前为止得到最大的长度。每次遇到0时,第一个变量重新从0开始计数。
代码:
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int num = 0;
int max = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == 1)
{
num++;
if (num > max)
{
max = num;
}
}
else
{
num = 0;
}
}
return max;
}
};