Java/485. Max Consecutive Ones 最大连续1的个数

题目

Java/485. Max Consecutive Ones 最大连续1的个数_第1张图片


Java/485. Max Consecutive Ones 最大连续1的个数_第2张图片

 

 

 

代码部分一(4ms 96.65%)

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int res = 0;
        int now = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] == 0){
                now = 0;
            }else{
                now++;
                res = now > res ? now : res;
            }
        }
        
        
        return res;
    }
}

 

代码部分二(7ms 65.95%)

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int res = 0;
        int now = 0;
        boolean flag = false;
        if(nums[0] == 1){
            flag = true;
            now++;                
        }
            
        for(int i = 1; i < nums.length; i++){
            if(nums[i] == 1) flag = true;
            if(nums[i - 1] == 0 && nums[i] == 1) now++;
            if(nums[i - 1] == 1 && nums[i] == 1) now++;
            if(nums[i] == 0 || (nums[i] ==1 && i == (nums.length - 1)) ){
                if(now  > res) res = now;
                now = 0;
            }
            
        }
        
        if(res == 0 && flag){
            return 1;
        }
        
        
        return res;
    }
}

 

你可能感兴趣的:(算法,简单,Max,Consecutive,Ones,最大连续1的个数)