文章目录
- 题目链接:
- 题目描述:
- 解法
- C++ 算法代码:
- 图解
题目链接:
1004. 最大连续 1 的个数 III
题目描述:
解法
解法一:暴力枚举+
zero
计数器转化找出最长的子数组,
0
的个数不超过k
个。
例如:nums = [1,1,1,0,0,0,1,1,1,1,0], K = 2
解法二:滑动窗口
left = 0,right = 0
进窗口:
left
指向1
无视,指向0
计数器+1
判断(
0的个数>k
)->出窗口,不断循环更新结果
等到
right
指向最后的时候,结束更新
C++ 算法代码:
class Solution
{
public:
int longestOnes(vector<int>& nums, int k)
{
int ret = 0;
for(int left = 0, right = 0, zero = 0; right < nums.size(); right++)
{
if(nums[right] == 0) zero++; // 进窗口
while(zero > k) // 判断
if(nums[left++] == 0) zero--; // 出窗口
ret = max(ret, right - left + 1); // 更新结果
}
return ret;
}
};
图解
例如:nums = [1,1,1,0,0,0,1,1,1,1,0], K = 2
ret = 0,left = 0, right = 0, zero = 0
,ret = max(ret, right - left + 1) = 1
,right++,right = 1
ret = 1,left = 0, right = 1, zero = 0
,ret = max(ret, right - left + 1) = 2
,right++,right = 2
ret = 2,left = 0, right = 2, zero = 0
,ret = max(ret, right - left + 1) = 3
,right++,right = 3
-
ret = 3,left = 0, right = 3, zero = 0
,nums[right] == 0 ->zero++,zero=1
ret = max(ret, right - left + 1) = 4
,right++,right = 4
-
ret = 4,left = 0, right = 4, zero = 1
,nums[right] == 0 ->zero++,zero=2
ret = max(ret, right - left + 1) = 5
,right++,right = 5
-
ret = 5,left = 0, right = 5, zero = 2
,nums[right] == 0 ->zero++,zero=3
while(zero > k){ // 判断 if(nums[left++] == 0){ zero--; } }
zero = 2,left = 4
ret = max(ret, right - left + 1) = 5
,right++,right = 6
- 后面流程一样,就不多赘述了。