zoukankan      html  css  js  c++  java
  • 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?

    本题我开始用了一个方法跑了出来,但是对于one变成了多个的话就解决不了了,后来看了答案,发现可以用zero来表示出现zero的个数,然后while zero出现的次数大于k的时候把后面的指针往前移。代码如下:

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

    对于出现的follow up,可以使用一个queue来做,其他的方法还是上面的方法,代码如下:

     1 public class Solution {
     2     public int findMaxConsecutiveOnes(int[] nums) {
     3         Queue<Integer> q = new LinkedList<Integer>();
     4         int hi = 0;
     5         int lo = 0;
     6         int len = 0;
     7         for(;hi<nums.length;hi++){
     8             if(nums[hi]==0){
     9                 q.offer(hi);
    10             }
    11             while(q.size()>1){
    12                 lo = q.poll()+1;
    13             }
    14             len = Math.max(len,hi-lo+1);
    15         }
    16         return len;
    17     }
    18 }
  • 相关阅读:
    算法:javascript截取字符串
    【转】解决memcached启动失败
    Ubuntu 16.04 安装 Apache, MySQL, PHP7
    phpstorm2016.3+xdebug调试
    (转)微信开发连接SAE数据库
    php图片上传服务器
    大数据整体市场规模达1000亿,金融、政务等行业应用占据七成份额
    “AI智客计划”
    人工智能 :眼纹识别技术大显神通,一眼认出你
    AI 芯片,是金山还是泡沫?
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6512811.html
Copyright © 2011-2022 走看看