leetcode (Max Consecutive Ones)

Title:Max Consecutive Ones    485

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/max-consecutive-ones/

 

1. 将每次连续遍历到1,都放入list中,同时对连续遍历到1后作加加操作,最后遍历list,找到最大的值。这样的可能性list会超级大,最大会是数组长度的平方。

时间复杂度:O(n),两次for循环,但都是一层。

空间复杂度:O(n^2),申请的list,最大是数组长度的平方。

    /**
     * 将每次连续遍历到1,都放入list中,同时对连续遍历到1后作加加操作,最后遍历list,找到最大的值
     * @param nums
     * @return
     */
    public static int findMaxConsecutiveOnes(int[] nums) {

        if (nums == null || nums.length <= 0) {
            return 0;
        }

        int max= 0;
        List<Integer> list = new ArrayList<>();

        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 1) {
                max++;
                list.add(max);
            }
            else {
                list.add(max);
                max = 0;
            }
        }

        int m = list.get(0);
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i) >= m) {
                m = list.get(i);
            }
        }

        return m;

    }

2. 定义变量max作为连续的最大数,定义变量count作为当前连续1的个数,每次遍历后,都将max与count比较大小。

时间复杂度:O(n),一次一层for循环,最长遍历是数组的长度。

控价复杂度:O(1),没有申请额外的空间。

    /**
     * 变量max作为连续的最大数,每次遍历都进行比较
     * 变量count作为当前连续1的个数
     * @param nums
     * @return
     */
    public static int findMaxConsecutiveOnes1(int[] nums) {

        if (nums == null || nums.length <= 0) {
            return 0;
        }

        int max = Integer.MIN_VALUE;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 1) {
                count++;
            }
            else {
                count = 0;
            }
            max = count > max ? count : max;
        }

        return max;

    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鬼王呵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值