zoukankan      html  css  js  c++  java
  • Leetcode 1004 Max Consecutive Ones III (滑动窗口)

    Leetocde 1004

    题目描述

    Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
    
    Return the length of the longest (contiguous) subarray that contains only 1s. 
    

    例子

    Example 1:
    Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
    Output: 6
    Explanation: 
    [1,1,1,0,0,1,1,1,1,1,1]
    Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.
    
    Example 2:
    Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
    Output: 10
    Explanation: 
    [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
    Bolded numbers were flipped from 0 to 1.  The longest subarray is underlined.
    

    方法

    ** Solution Java **
    ** 2ms, beats 99.68% **
    ** 42MB, beats 100.00% **
    class Solution {
        public int longestOnes(int[] A, int K) {
            int n = A.length, res = 0;
            for (int i = 0, j = 0; j < n; ++j) {
                if (A[j] == 0)
                    --K;
                while (K == -1) 
                    if (A[i++] == 0)
                        ++K;
                res = Math.max(res, j - i + 1);
            }
            return res;
        }
    }
    
    ** 简化版 **
    class Solution {
        public int longestOnes(int[] A, int K) {
            int i = 0, j = 0;
            for (; j < A.length; ++j) {
                if (A[j] == 0)  --K;
                if (K < 0 && A[i++] == 0) ++K;
            }
            return j - i;
        }
    }
    
    ** Solution Python3 **
    ** 608ms, beats 91.07% **
    ** 13.6MB, 50.00% **
    class Solution:
        def longestOnes(self, A: List[int], K: int) -> int:
            i = 0
            for j in range(len(A)) :
                if (A[j] == 0) :
                    K -= 1
                if (K < 0) :
                    if (A[i] == 0) :
                        K += 1
                    i += 1
            return j - i + 1
    
    ** 简化版 **
    class Solution:
        def longestOnes(self, A: List[int], K: int) -> int:
            i = 0
            for j in range(len(A)) :
                K -= 1 - A[j]
                if (K < 0) :
                    K += 1 - A[i]
                    i += 1
            return j - i + 1
    
  • 相关阅读:
    c#获取指定时区的日期
    项目版本管理
    iis部署网站
    浏览器测试string是否为图片
    网站中挂视频
    百度地图调用
    mvc actionresult返回各种文件
    Coursera机器学习week7 单元测试
    Coursera机器学习week7 笔记
    牛客练习赛12 AB
  • 原文地址:https://www.cnblogs.com/willwuss/p/12521354.html
Copyright © 2011-2022 走看看