Given a binary array, find the maximum number of consecutive 1s in this array if you can flip at most one 0.
Example 1:
Input: [1,0,1,1,0] Output: 4 Explanation: Flip the first zero will get the the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4.
Note:
- The input array will only contain
0
and1
. - The length of input array is a positive integer and will not exceed 10,000
Follow up:
What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?
最大连续1的个数 II。
给定一个二进制数组,你可以最多将 1 个 0 翻转为 1,找出其中最大连续 1 的个数。
思路是滑动窗口。这道题可以抽象成你需要找一个最长的子数组,里面最多只能有一个0。这道题我们需要一个queue记录所有遍历到的0的位置,而且queue的size不能大于1。当queue.size() > 1的时候,我们需要结算一下当前最大的满足题意的子串长度是多少。结算完毕之后,需要把左指针移动到当前这个0的右边,这也是使用队列的巧妙之处。
时间O(n)
空间O(n)
Java实现
1 class Solution { 2 public int findMaxConsecutiveOnes(int[] nums) { 3 int max = 0; 4 // 保持queue中只有一个1 5 // 等价于滑动窗口找子串,子串内最多只能有一个1 6 int k = 1; 7 Queue<Integer> zeroIndex = new LinkedList<>(); 8 for (int l = 0, h = 0; h < nums.length; h++) { 9 if (nums[h] == 0) { 10 zeroIndex.add(h); 11 } 12 if (zeroIndex.size() > k) { 13 l = zeroIndex.remove() + 1; 14 } 15 max = Math.max(max, h - l + 1); 16 } 17 return max; 18 } 19 }