LeetCode 485. Max Consecutive Ones

来源:互联网 发布:暖通工程预算软件 编辑:程序博客网 时间:2024/05/20 07:33

问题描述

Given a binary array, find the maximum number of consecutive 1s in this array.
Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
The maximum number of consecutive 1s is 3.

Note:

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

问题分析

给定一个数组nums,nums中包括了0和1的序列。求出当前数组最长的1的序列。

代码实现

public int findMaxConsecutiveOnes(int[] nums) {        if (nums == null || nums.length == 0) {            return 0;        }        int maxLen = 0;        int subLen = 0;        for (int i = 0; i < nums.length; i++) {            while (i < nums.length && nums[i] == 1) {                subLen++;                i++;            }            if (subLen > maxLen) {                maxLen = subLen;            }            subLen = 0;        }        return maxLen;    }