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就可以了。

  • 相关阅读:
    linux 学习随笔-shell基础知识
    linux 学习随笔-压缩和解压缩
    解析xml的4种方法详解
    集合工具类
    Map概述
    List集合概述
    Java集合框架
    Spring JdbcTemplate详解
    关于c3p0数据库连接池的简单使用
    Java通过JDBC封装通用DAO层
  • 原文地址:https://www.cnblogs.com/kevincong/p/7874906.html
Copyright © 2011-2022 走看看