zl程序教程

您现在的位置是:首页 >  其他

当前栏目

​LeetCode刷题实战485:最大连续 1 的个数

2023-04-18 16:55:48 时间

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 最大连续 1 的个数,我们先来看题面:

https://leetcode-cn.com/problems/max-consecutive-ones/

Given a binary array nums, return the maximum number of consecutive 1's in the array.

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

示例

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

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

解题

这是一道简单题,直接看代码就行了 。

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

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-480题汇总,希望对你有点帮助!

LeetCode刷题实战481:神奇字符串

LeetCode刷题实战482:密钥格式化

LeetCode刷题实战483:最小好进制

LeetCode刷题实战484:寻找排列