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

  • 相关阅读:
    批量管理增量日志(seek、tell)
    字符串和编码
    5.activiti--完成任务
    4.activiti--代理任务Claiming the task
    3.activiti--待办任务
    2.activiti-启动流程实例
    1.activiti-流程图
    html 各种高度
    redis-过期时间、访问限制与缓存
    spring mvc controller 接收参数
  • 原文地址:https://www.cnblogs.com/hzg1981/p/8818499.html
Copyright © 2011-2022 走看看