zoukankan      html  css  js  c++  java
  • LeetCode 485 Max Consecutive Ones

    题目:

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

    Example 1:

    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

    分析

    first try:

    class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int startPntr =0, endPntr =0;
            
            int length = nums.length;
            int maxCount = 0;
            for(int i=0; i<length; i++) {
                if(nums[i] == 0) {
                    if(maxCount < endPntr-startPntr){
                        maxCount = endPntr-startPntr;
                    }
                    startPntr = i+1;
                    endPntr = i+1;
                } else {
                    endPntr++;
                }
            }
            
            return maxCount;
        }
    }

    结果:

    Submission Result: Wrong Answer 
    Input: [1]
    Output: 0
    Expected: 1

    二次:

    class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int startPntr =0, endPntr =0;
            
            int length = nums.length;
            int maxCount = 0;
            for(int i=0; i<length; i++) {
                if(nums[i] == 0) {
                    if(maxCount < endPntr-startPntr){
                        maxCount = endPntr-startPntr;
                    }
                    startPntr = i+1;
                    endPntr = i+1;
                } else {
                    endPntr++;
                    
                    if(i==length-1){
                        if(maxCount < endPntr-startPntr){
                            maxCount = endPntr-startPntr;
                        } 
                    }
                }
            }
            
            return maxCount;
        }
    }

    result:

    分析:

    需要考虑1作为结尾的情况。

  • 相关阅读:
    定义和使用EL函数
    在Java Web程序中使用Hibernate
    JDBC在Java Web中的应用——分页查询
    JDBC调用存储过程
    使用navicat工具创建MySQL存储过程
    JDBC操作数据库的批处理
    JDBC操作数据库
    Servlet监听器统计在线人数
    Servlet字符编码过滤器
    Servlet过滤器创建与配置
  • 原文地址:https://www.cnblogs.com/hzg1981/p/8818499.html
Copyright © 2011-2022 走看看