【java】leetcode1004. 最大连续1的个数 III;2024. 考试的最大困扰度

由于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;
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值