1
头图

Maximum number of consecutive 1s

Topic description: Given a binary array, calculate the maximum number of consecutive 1s in it.

For example descriptions, please refer to the official website of LeetCode.

Source: LeetCode
Link: https://leetcode-cn.com/problems/max-consecutive-ones/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.

Solution 1: Array Traversal

First of all, consider the special case, if the original array is empty, it is impossible to have consecutive 1, and return 0 directly.

Otherwise, traverse the array and record the maximum length of consecutive 1 occurrences in each wave, and return it at last.

 public class LeetCode_485 {
    /**
     * 数组遍历
     *
     * @param nums 原数组
     * @return
     */
    public static int findMaxConsecutiveOnes(int[] nums) {
        // 如果原数组为空,不可能有连续的1,直接返回0
        if (nums == null || nums.length == 0) {
            return 0;
        }
        // 记录最长连续1的个数
        int max = 0;
        // 记录上一个数的值是0还是1;记录上一个数(如果是1)连续出现的次数
        int curNum = 0, curCount = 0;
        // 遍历数组
        for (int i = 0; i < nums.length; i++) {
            if (curNum == 0 && nums[i] == 0) {
                // 如果上一个数是0而且当前索引的数也是0,则跳过
                continue;
            } else if (curNum == 0 && nums[i] == 1) {
                // 如果上一个数是0且当前索引的数是1,则当前数字是新的连续的1的起点,更新curNum和curCount的值
                curNum = 1;
                curCount++;
            } else if (curNum == 1 && nums[i] == 0) {
                // 如果上一个数是1而且当前索引的数是0,则上一个数是上一波连续的1的终点,判断连续的个数是否比max大,如果是,更新之;并更新curNum和curCount的值
                max = Math.max(max, curCount);
                curNum = 0;
                curCount = 0;
            } else if (curNum == 1 && nums[i] == 1) {
                // 如果上一个数是1而且当前索引的数也是1,则更新curCount的值
                curCount++;
            }
        }
        // 最后,返回max和可能的最后一波连续的1的个数的较大值
        return Math.max(curCount, max);
    }

    public static void main(String[] args) {
        int[] nums = {1, 1, 0, 1, 1, 1};
        // 测试用例,期望输出: 3
        System.out.println(findMaxConsecutiveOnes(nums));
    }
}
[Daily Message] Failure is a comma for the strong and a period for the weak.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!