LintCode: 883 Max Consecutive Ones

分析:本题题意是找到连续的1的个数,有1次将0翻转为1的机会。用一个通解来处理此类问题,k为可翻转的机会数目。此题k=1.

可以维护一个[left,right]的移动窗口来容纳k个0,遍历右边界,每当遇到0,就累加zero的个数,然后判断此时0的个数是否大于k,若大于k,则右移左边界left使其满足窗口内有k个0,如果移除掉的nums[left]为0,则zero--。然后用窗口中的数字个数来更新res。

public class Solution {
    /**
     * @param nums: a list of integer
     * @return: return a integer, denote  the maximum number of consecutive 1s
     */
    public int findMaxConsecutiveOnes(int[] nums) {
        // write your code here
        int left=0,numOfzero=0,k=1,res=0;
        for(int right=0;right<nums.length;right++){
            if(nums[right]==0)  ++numOfzero;
            while(numOfzero>k){
                if(nums[left++]==0){
                    numOfzero--;
                }
            }
            res=Math.max(res,right-left+1);
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_27139155/article/details/80401688