zoukankan      html  css  js  c++  java
  • [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的右边,这也是使用队列的巧妙之处。

    时间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 }

    sliding window相关题目

    LeetCode 题目总结

  • 相关阅读:
    2-Rsync备份-全网备份
    1-Rsync备份-备份概述
    复杂声明学习总结
    EasyExcel的用法
    listvue
    解决Error: Cannot find module 'node-sass'问题
    Webpack
    babel的使用
    nodejs的使用
    vue入门
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14238833.html
Copyright © 2011-2022 走看看