zoukankan      html  css  js  c++  java
  • leetCode-Max Consecutive Ones

    Description:
    Given a binary array, find the maximum number of consecutive 1s in this array.

    Example1:

    Input: [1,1,0,1,1,1]
    Output: 3
    Explanation: The first two digits or the last three digits are consecutive 1s.
        The maximum number of consecutive 1s is 3.

    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

    My Solution:

    class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int count = 0;
            int maxN = 0;
            for(int i : nums){
                if(i == 1){
                    count++;
                     if(count > maxN){
                        maxN = count;
                    }
                }else{
    
                    count = 0;
                }
            }
            return maxN;
        }
    }

    改进:

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int result = 0;
            int count = 0;
    
            for (int i = 0; i < nums.length; i++) {
                if (nums[i] == 1) {
                    count++;
                    //替换为了Math.max()函数,更简洁
                    result = Math.max(count, result);
                }
                else count = 0;
            }
    
            return result;
        }
    }

    总结:
    注意每次碰到1的时候增加count,然后求max(count,maxN),然后每次num = 0将count置0就可以了。

  • 相关阅读:
    XML Schema (1)
    xml
    java输入输出流(内容练习)
    Java中I/O的分析
    java File类
    java中Map的用法(HaspMap用法)
    Git
    oracle安装分析
    博客第一天
    正则化 L1 L2
  • 原文地址:https://www.cnblogs.com/kevincong/p/7874906.html
Copyright © 2011-2022 走看看