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

  • 相关阅读:
    windows下vagrant使用及工作环境配置
    使用docker搭建lnmp环境
    Docker常用命令
    [docker] 管理docker容器中的数据
    python初始化父类错误
    Linux--
    用少于2MB内存存下5百万个介于0到1千万之间的整数
    k路归并:数组、链表
    剑指offer新思路
    阿里电话面试
  • 原文地址:https://www.cnblogs.com/hzg1981/p/8818499.html
Copyright © 2011-2022 走看看