leetcode (Max Consecutive Ones)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/84528195

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;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/84528195