LeetCode 1004. 最大连续1的个数 III

news/2024/5/20 7:06:35 标签: 滑动窗口

原题目:https://leetcode-cn.com/problems/max-consecutive-ones-iii/

 

思路:

滑动窗口

 

代码:

class Solution {
public:
    int longestOnes(vector<int>& A, int K) {
        int maxlen =0;
        int left=0,right=0;
        while(right<A.size()){
            if(A[right]==0){
                //不可以变换,找出第一个变换过的0,越过他,变换现在的0.
                if(K==0){
                    while(A[left]==1) left++;
                    left++;
                }
                //可以将0变为1,
                else{
                    K--;
                }
            }
            maxlen = max(maxlen,++right - left);
        }
        return maxlen;
    }
};

 


http://www.niftyadmin.cn/n/898952.html

相关文章

LeetCode 1382. 将二叉搜索树变平衡

原题目&#xff1a;https://leetcode-cn.com/problems/balance-a-binary-search-tree/ 思路&#xff1a; 获取中序遍历的结果&#xff0c;然后找去中点&#xff0c;此为根节点&#xff0c;依次递归的构造左子树和右子树 代码: class Solution { public:vector<int> ino…

LeetCode 1267. 统计参与通信的服务器

原题目&#xff1a;https://leetcode-cn.com/problems/count-servers-that-communicate/ 思路&#xff1a; 记录每行每列的计算机的个数&#xff0c;然后依次遍历节点&#xff0c;如果该节点为计算机并且该行或该列的计算机个数大于1&#xff0c;则表示可以通信 代码L&#xf…

LeetCode 47. 全排列 II

原题目&#xff1a;https://leetcode-cn.com/problems/permutations-ii/ 思路&#xff1a; 对于全排列的扩展&#xff0c;只需要加上防重的判定条件 代码&#xff1a; class Solution {vector<int> vis;public:void backtrack(vector<int>& nums, vector<…

LeetCode 404. 左叶子之和

原题目&#xff1a;https://leetcode-cn.com/problems/sum-of-left-leaves/ 思路&#xff1a; 递归的思想&#xff0c;只计算左叶子的节点值&#xff0c;那么怎么判断是不是左叶子呢&#xff0c;即当前节点指向的做孩子不为空&#xff0c;且做孩子是叶子节点&#xff0c;他就是…

LeetCode 1313. 解压缩编码列表

原题目&#xff1a;https://leetcode-cn.com/problems/decompress-run-length-encoded-list/ 代码: class Solution { public:vector<int> decompressRLElist(vector<int>& nums) {vector<int> ans;for(int i1;i<nums.size();i2){for(int j0;j<nu…

LeetCode 968. 监控二叉树

原题目&#xff1a;https://leetcode-cn.com/problems/binary-tree-cameras/ 思路: 节点分为三种状态&#xff0c; 1&#xff1a;该节点安装了监视器 2&#xff1a;该节点可观&#xff0c;但没有安装监视器 3&#xff1a;该节点不可观 代码&#xff1a; class Solution {int …

LeetCode 617. 合并二叉树

原题目&#xff1a;https://leetcode-cn.com/problems/merge-two-binary-trees/ 思路&#xff1a; 构造新的节点&#xff0c;判断递归的终止条件就可以 代码&#xff1a; class Solution { public:TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {if(t1 nullptr) return …

LeetCode 896. 单调数列

原题目&#xff1a;https://leetcode-cn.com/problems/monotonic-array/ 思路&#xff1a; 使用两个flag&#xff08;a和b&#xff09;来表明里面存在增和减的情况&#xff0c;如果两者同时出现&#xff0c;那么就不单调 代码&#xff1a; class Solution { public:bool isMo…