BiruLyu
7/14/2017 - 6:24 PM

487. Max Consecutive Ones II(#).java

public int findMaxConsecutiveOnes(int[] nums) {                 
        int max = 0, k = 1; // flip at most k zero
        Queue<Integer> zeroIndex = new LinkedList<>(); 
        for (int l = 0, h = 0; h < nums.length; h++) {
            if (nums[h] == 0)
                zeroIndex.offer(h);
            if (zeroIndex.size() > k)                                   
                l = zeroIndex.poll() + 1;
            max = Math.max(max, h - l + 1);
        }
        return max;                     
    }
public class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int indexOfZero = -1;
        int start = 0;
        int max = 0;
        for(int i=0; i< nums.length; i++) {
            if(nums[i] == 0) {
                if( indexOfZero >= 0) {
                    max = Math.max(max, i-start);
                    start = indexOfZero +1;
                }
                indexOfZero = i;
            }
        }
        max = Math.max(max, nums.length - start);
        return max;
    }
}
/*Sliding Window*/
public class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        if (nums == null || nums.length < 1) return 0;
        int len = nums.length;
        int start = 0;
        int end = 0;
        int count = 0;
        int res = 0;
        while (end < len) {
            //if (nums[end++] == 1) continue;
            if (nums[end++] == 0) {
                count++;
            }
            while (count > 1) {
                if (nums[start++] == 0) count--;
            }
            res = Math.max(res, end - start);
        }
        return res;
    }
}