由于1004与2024题解题思路较为相似,因此总结在一起
leetcode1004. 最大连续1的个数 III:
问题描述
解题思路:
把 最多可以把 K 个 0 变成 1,求仅包含 1 的最长子数组的长度 转换为 找出一个最长的子数组,该子数组内最多允许有 K 个 0 。
本题是求最大连续子区间,可以使用滑动窗口方法。滑动窗口的限制条件是:窗口内最多有 K 个 0。
实现代码:
class Solution {
public int longestOnes(int[] A, int K) {
int N = A.length;
int res = 0;
//保存最大的满足题目要求的 子数组/子串 长度
int left = 0, right = 0;
int zeros = 0;
while (right < N) {
//第一重 while 循环是为了判断 right 指针的位置是否超出了数组边界
if (A[right] == 0)
zeros ++;
while (zeros > K) {
//第二重 while 循环是让 left 指针向右移动到 [left, right] 区间符合题意的位置
if (A[left++] == 0)
zeros --;
}
res = Math.max(res, right - left + 1);
right ++;
}
return res;
}
}
leetcode2024. 考试的最大困扰度:
问题描述
实现代码:
class Solution {
public int maxConsecutiveAnswers(String answerKey, int k) {
return Math.max(maxAnswer(answerKey,k,'T'),maxAnswer(answerKey,k,'F'));
}
public int maxAnswer(String answerKey, int k,char ch){
int res=0;
int m=0;
for(int left=0,right=0;right<answerKey.length();right++){
res+=answerKey.charAt(right)!=ch?1:0;
while(res>k){
res-=answerKey.charAt(left++)!=ch?1:0;
}
m=Math.max(m,right-left+1);
}
return m;
}
}