LeetCode 485 最大连续1的个数

题目

Given a binary array, find the maximum number of consecutive 1s in this array.

大致题意

给定一个0,1数组,找到数组中最长连续1的长度。

解题思路

遍历这个数组如果为1,则计数加一,如果不为一,则清空计数器,最后最大值为之前设定的最大值和计数器之间的较大者。代码如下:

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

拓展

如果给定的数组还有各种各样的数,找到最长的连续相同数的长度。那么这样就需要再添加一个变量,记录上一个标准值。然后如果下一个值与标准值相同,那么计数器加一;如果不相同,改变标准值为当前值,且将计数器清0。之后的操作和这个类似。

猜你喜欢

转载自blog.csdn.net/ch_609583349/article/details/77529120