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

posted @ 2018-04-13 13:20  Zhao_Gang  阅读(98)  评论(0编辑  收藏  举报