LeetCode 485. 最大连续1的个数
原题链接
简单
作者:
bruce
,
2021-01-29 00:36:48
,
所有人可见
,
阅读 353
#include <iostream>
#include <vector>
using namespace std;
/**
* 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最多的次数
*/
/**
* 方法 1,
*/
int findMaxConsecutiveOnes1(vector<int> &nums)
{
int res = 0, ans = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == 1)
{
res++;
ans = max(res, ans);
}
else
res = 0;
// ans = max(res, ans); // 放这里都一样
}
return ans;
}
/**
* 方法 2,有连续出现的数字就会记录。
* */
int findMaxConsecutiveOnes2(vector<int> &nums)
{
int count = 0, maxnum = 0;
if (nums.size() == 1)
return 1;
if (nums.size() > 1)
{
for (int i = 1; i < nums.size(); i++)
{
int flag = i - 1;
if (nums[i] == nums[flag])
count += 1;
else
{
if (count >= maxnum)
maxnum = count;
count = 1;
}
}
}
return max(maxnum, count);
}
/**
* 方法 3,这个思路都是一样的
* */
int findMaxConsecutiveOnes4(vector<int> &nums)
{
if (nums.size() == 1)
return nums[0] == 1 ? 1 : 0;
int count = 0, maxnum = 0;
for (int i = 0; i < nums.size(); i++)
{
count = (nums[i] + count) * nums[i];
maxnum = max(maxnum, count);
}
return maxnum;
}