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

猜你喜欢

转载自www.cnblogs.com/willwuss/p/12521354.html