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 <= A.length <= 20000
0 <= K <= A.length
A[i]
is0
or1
這道題是之前那道 Max Consecutive Ones II 的拓展,博主在之前的解法二中就預言了翻轉k次的情況,果不其然,在五百多道題之后,該來的還是來了。不過不要緊,我們已經知道了該如何應對了,直接上滑動窗口 Sliding Window,用個變量 cnt 記錄當前將0變為1的個數,在遍歷數組的時候,若遇到了0,則 cnt 自增1。若此時 cnt 大於K了,說明該縮小窗口了,用個 while 循環,若左邊界為0,移除之后,此時 cnt 應該自減1,left 自增1,每次用窗口大小更新結果 res 即可, 參見代碼如下:
解法一:
class Solution {
public:
int longestOnes(vector<int>& A, int K) {
int n = A.size(), left = 0, cnt = 0, res = 0;
for (int i = 0; i < n; ++i) {
if (A[i] == 0) ++cnt;
while (cnt > K) {
if (A[left] == 0) --cnt;
++left;
}
res = max(res, i - left + 1);
}
return res;
}
};
我們也可以寫的更簡潔一些,不用 while 循環,但是還是用的滑動窗口的思路,其中i表示左邊界,j為右邊界。在遍歷的時候,若遇到0,則K自減1,若K小於0了,且 A[i] 為0,則K自增1,且i自增1,最后返回窗口的大小即可,參見代碼如下:
解法二:
class Solution {
public:
int longestOnes(vector<int>& A, int K) {
int n = A.size(), i = 0, j = 0;
for (; j < n; ++j) {
if (A[j] == 0) --K;
if (K < 0 && A[i++] == 0) ++K;
}
return j - i;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1004
類似題目:
Number of Substrings Containing All Three Characters
Count Number of Nice Subarrays
Replace the Substring for Balanced String
Shortest Subarray with Sum at Least K
Longest Substring with At Most Two Distinct Characters
Longest Substring with At Least K Repeating Characters
Longest Substring with At Most K Distinct Characters
參考資料:
https://leetcode.com/problems/max-consecutive-ones-iii/