Leetcode 1004. 最大連續1的個數 III (雙指標)
阿新 • • 發佈:2021-02-20
Description
Solution
顯然滿足雙指標中的單調性,即左指標+1的情況下,右指標(非嚴格)遞增
Code
class Solution {
public:
int longestOnes(vector<int>& A, int K) {
int l = 0, r = 0, res = 0;
int cnt = K, n = A.size();
if(!K) {
int tmp = 0;
for(int i = 0;i < n;++i) {
if(!A[i]) continue;
tmp = 0;
while(i < n && A[i]) {
tmp++;i++;
}res = max(res, tmp);
}return res;
}
if(!A[0]) {
cnt--;
}
while(l < n) {
while(r + 1 < n) {
if(A[r+1]) {
r++;
} else {
if(cnt) cnt--,r++;
else break;
}
}
res = max(res, r - l + 1);
if(!A[l]) cnt++;
l++ ;
}return res;
}
};