LeetCode485. Max Consecutive Ones

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43274298/article/details/102692004

给定一个二进制数组, 计算其中最大连续1的个数。

示例 1:

输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意:

输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。

解题思路:定义一个值来记录是否连续

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int max1 = 0;
        int ans = 0;
        int max2 = 0;
        for(int i = 0; i < nums.length; i++){
            if((ans == 1) && (nums[i] == 1)){
                max2++;
            }else if((ans == 1) && (nums[i] == 0)){
                max1 = Math.max(max1,max2);
                max2 = 0;
                ans = 0;
            }else if((ans == 0) && (nums[i] == 1)){
                ans = 1;
                max2++;
            }else{
                ;
            }
        }
        max1 = Math.max(max1,max2);
        return max1;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43274298/article/details/102692004