【LeetCode】1004. Max Consecutive Ones III(滑动窗口)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hh66__66hh/article/details/88109264

【LeetCode】1004. Max Consecutive Ones III(滑动窗口)

题目

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.

Note:
(1)1 <= A.length <= 20000
(2)0 <= K <= A.length
(3)A[i] is 0 or 1

题意

这题的意思是,数组A由 0 和 1 组成,我们可以将其中的 K 个 0 转换成 1.
该题要求的是转换后的数组中只包含 1 的字串的最大长度。

思路

这题首先要明确一点,为了得到最长的只包含 1 的字串,这 K 次转换后得到的 1 必须是在一个块里的。具体过程看代码。

代码

class Solution {
public:
    int longestOnes(vector<int>& A, int K) {
        int i, j, a, b, c, maxl, curl;
        queue<int>q;

		// 初始化队列
        while(!q.empty()) {
            q.pop();
        }

        curl = 0; //当前只包含1的子串的长度
        maxl = 0; //最长的只包含1的子串的长度
        c = K; //还有c次机会可由0转为1
        for(i=0; i<A.size(); i++) {
            if(A[i] == 0) {
                if(K == 0) {
                    if(curl > maxl) {
                        maxl = curl;
                    }
                    curl = 0;
                    continue;
                }
                if(c > 0) {
                    curl++;
                    c--;
                    q.push(i);
                }
                else {
                    if(maxl < curl) {
                        maxl = curl;
                    }
                    //此时相当于将子串开头的1挪到最后,因此长度一样
                    curl = i - q.front();
                    q.pop();
                    q.push(i);
                }
            }
            else {
                curl++;
            }
        }
        if(curl > maxl) {
            maxl = curl;
        }
        return maxl;
    }
};

猜你喜欢

转载自blog.csdn.net/hh66__66hh/article/details/88109264