天天看点

晨哥Leetcode: sliding window滑动窗口套路

for循环用end指针一直向后,当窗口不再满足条件时,内部while循环解决start指针

以下模板应背诵:

1004. Max Consecutive Ones III

int res = 0;
        int start = 0, count = 0;
        for(int end = 0; end< a.length; end++) {//end指针去开路,一直向右遍历
            if(a[end] == 0) count++; //end指针每到一步,做相应Update
            while(count > k) {  //当这个窗口不再满足条件了,while循环移动start指针
                if(a[start++] == 0) count--;
            }
            res = Math.max(res, end-start+1); //此时窗口条件是满足的,求解吧,放到最后再求解
        }
           

继续阅读