1004. 最大连续1的个数 III
如题:
给定一个由若干
0和1组成的数组A,我们最多可以将K个值从0变成1。
返回仅包含1的最长(连续)子数组的长度。
滑动窗口
class Solution {
public:
int longestOnes(vector<int>& A, int K) {
int count = 0;
int left = 0;
int right = 0;
int res;
while (right < A.size())
{
if (A[right] == 1)
{
count++;
}
if (count + K <= right - left)
{
if (A[left] == 1) count--;
left++;
}
right++;
res = max(res, right - left);
}
return res;
}
};
这篇博客介绍了如何利用滑动窗口算法解决在给定0和1组成的数组中,最多可将K个0变为1的情况下,找到最长全为1的子数组长度的问题。代码示例给出了C++实现,通过维护左右指针和计数器来动态更新最大子数组长度。
2091

被折叠的 条评论
为什么被折叠?



