Every day a Leetcode
题目来源:485. 最大连续 1 的个数
解法1:遍历
为了得到数组中最大连续1的个数,需要遍历数组,并记录最大的连续1的个数和当前的连续1的个数。如果当前元素是1,则将当前的连续1的个数加1,否则,使用之前的连续1的个数更新最大的连续1的个数,并将当前的连续1的个数清零。
遍历数组结束之后,需要再次使用当前的连续1的个数更新最大的连续1的个数,因为数组的最后一个元素可能是1,且最长连续1的子数组可能出现在数组的末尾,如果遍历数组结束之后不更新最大的连续1的个数,则会导致结果错误。
代码:
/*
* @lc app=leetcode.cn id=485 lang=cpp
*
* [485] 最大连续 1 的个数
*/
// @lc code=start
class Solution
{
public:
int findMaxConsecutiveOnes(vector<int> &nums)
{
int maxCount = 0;
int count = 0;
int n = nums.size();
for (int i = 0; i < n; i++)
{
if (nums[i] == 1)
count++;
else
{
maxCount = max(maxCount, count);
count = 0;
}
}
maxCount = max(maxCount, count);
return maxCount;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(n),其中 n 是数组的长度。需要遍历数组一次。
空间复杂度:O(1)。