LeetCode每日一题: 最大连续1的个数(No.485)

题目:最大连续1的个数


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

示例:


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

思考:


这道题可以转换成字符串做,将数组转换成字符串然后以“0”分割,再取最长的子串长度及是结果。
复制代码

实现:


 class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int num : nums) {
            stringBuilder.append(num);
        }
        String[] split = stringBuilder.toString().split("0");
        int max = 0;
        for (String string : split) {
            if (string.length() > max) {
                max = string.length();
            }
        }
        return max;
    }
}
复制代码

再思考:


这道题也可以不用转字符串做。
首先定义两个变量max存放结果,temp存放临时长度。
循环遍历数组每个元素,为1则temp+1,为0则将temp与max比较,temp大于max就将max更新,然后将temp重置为0。
最后在循环外在将temp与max比较一次,大于max就将temp的值赋给max,这样是为了防止最后以1结尾的长度没被比较过。
复制代码

再实现:


class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int max = 0;
        int temp = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 1) {
                temp++;
            } else {
                if (temp > max) {
                    max = temp;
                }
                temp = 0;
            }
        }
        if (temp > max) {
            max = temp;
        }
        return max;
    }
}复制代码

转载于:https://juejin.im/post/5ca9adc86fb9a05e146d7fbe

你可能感兴趣的:(数据结构与算法)