485. Max Consecutive Ones
Given a binary array, find the maximum number of consecutive 1s in this array.
题目大意:给一个二进制数组,找到连续为1的最大数量
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
代码如下:
C++
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int Max = 0;//定义连续1的最大个数
int Min = 0;//暂时存储连续1的个数
int length = nums.size();
for(int i=0;i<length;i++)
{
if(!nums[i])//元素为0
{
if(Min > Max)
//暂时存储连续1的个数比之前的大,重新给Max赋值
Max = Min;
Min = 0;//重置Min
continue;
}
if(nums[i])//元素为1
Min++;
}
if(Min > Max)
Max = Min;
return Max;
}
};
下面贴出优化之前的代码
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int Max = 0;//定义连续1的最大个数
int Min = 0;//暂时存储连续1的个数
int length = nums.size();//数组长度
/*if (length == 1)//单元素数组
{
if(nums[0])//元素为1
{
Max = 1;
return Max;
}
else
{
Max = 0;
return Max;
}
}*/
for(int i=0;i<length;i++)
{
if(!nums[i])//元素为0
{
if(Min > Max)
//暂时存储连续1的个数比之前的大,重新给Max赋值并重置Min
{
Max = Min;
Min = 0;//重置Min
continue;
}
Min = 0;//重置Min
}
if(nums[i])//元素为1
{
Min++;
}
}
if(Min > Max)
Max = Min;
return Max;
}
};
碰到的问题:
- 7-19行代码用 38,39行完全可以代替。
- 第7行刚开始写成if (length),输出不是1就是0。最后才想起来length不为0均可执行花括号的内容,而非if(length == 1)
- 28,29行 31行重复执行了,优化后如第一个代码(if花括号的位置也很关键)