最大连续1的个数

此博客链接:https://www.cnblogs.com/ping2yingshi/p/12844969.html

最大连续1的个数(42min)

题目链接:https://leetcode-cn.com/problems/max-consecutive-ones/

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

示例 1:

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

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

题解:

        题意:统计数组中连续1最多的个数。

        思路:

                 1.定义一个统计连续1个数的变量count。

                 2,.定义一个统计最大连续1个数的变量maxcount。

                 3.遍历数组,当遇到1时,统计连续1个数,当遇到0时,把统计1个数清零。

                 4.比较统计1个数的值是否大于统计个数的最大值。

   代码如下:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int len=nums.length;
        if(len==1&&nums[0]==1)
           return 1;
        int count=0;
        int maxcount=0;
        int i=0;
        while(i<len)
        {
            if(nums[i]==1)
            {
                count++;
            }
            else 
            {
                count=0;
            }
            if(count>maxcount)
                   maxcount=count;
            i++;
        }
        return maxcount;
    }
}

 

posted @ 2020-05-07 19:08  萍2樱释  阅读(401)  评论(0编辑  收藏  举报