栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

0001力扣485题---最大连续1的个数

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

0001力扣485题---最大连续1的个数

485.最大连续 1 的个数

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

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

提示:1<=nums.length<=105 nums[i] 不是0就是1.


解题方法1:一次遍历法


方法代码:

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

在IDEA中验证java实例:

public class Main {
    public static void main(String[] args) {
        int[] nums = {0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1};
        Main solution = new Main();
        int x = solution.findMaxConsecutiveOnes(nums);
        System.out.println(x);
    }

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

编译并运行上面的程序,产生如下结果:
4

解题方法2:动态规划法

方法代码:

    public int findMaxConsecutiveOnes(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        nums[0] = nums[0] == 1 ? 1 : 0;
        int count = nums[0];

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/926504.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号