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作为结尾的情况。

  • 相关阅读:
    CSS选择器的权重与优先规则
    excel上传--phpExcel读取xls、xlsx
    反射与代理设计模式
    Map集合
    接口实际应用-工厂代理模式
    代码模型:对象比较
    Stream数据流
    集合输出接口-Iterator迭代输出-古老枚举输出:Enumeration
    Set集合接口-HashSet_TreeSet理解
    List类集接口-ArrayList
  • 原文地址:https://www.cnblogs.com/hzg1981/p/8818499.html
Copyright © 2011-2022 走看看