[LeetCode] 487. Max Consecutive Ones II

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 and 1.
  • 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 替换成 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> queue = new LinkedList<>();
 8         for (int l = 0, h = 0; h < nums.length; h++) {
 9             if (nums[h] == 0) {
10                 queue.add(h);
11             }
12             if (queue.size() > k) {
13                 l = queue.poll() + 1;
14             }
15             max = Math.max(max, h - l + 1);
16         }
17         return max;
18     }
19 }

 

我再提供一个类似 76 题的模板写法,这个写法可以直接套用到 1004 题上。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int findMaxConsecutiveOnes(int[] nums) {
 3         int res = 0;
 4         int count = 0;
 5         int start = 0;
 6         int end = 0;
 7         while (end < nums.length) {
 8             if (nums[end] == 0) {
 9                 count++;
10             }
11             end++;
12             while (count > 1) {
13                 if (nums[start] == 0) {
14                     count--;
15                 }
16                 start++;
17             }
18             res = Math.max(res, end - start);
19         }
20         return res;
21     }
22 }

 

sliding window相关题目

LeetCode 题目总结

posted @ 2021-01-06 01:14  CNoodle  阅读(143)  评论(0编辑  收藏  举报