题目描述

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

解法一

思路

只需要顺序遍历数组一遍就好了,result记录目前得到的最大的连续1的长度,count记录当前连续1的长度。对于每个元素:

  1. 如果元素为1,则count加一;
  2. 如果元素为0,则result更新为max(result, count)count清零;
  3. 遍历完成后再次将result更新为max(result, count)

Python

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result = 0
        count = 0
        for num in nums:
            if num == 0:
                result = max(result, count)
                count = 0
            else:
                count += 1
        result = max(result, count)
        return result

Java

public class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int result = 0;
        int count = 0;
        for (int num : nums) {
            if (num == 0) {
                result = Math.max(result, count);
                count = 0;
            } else {
                count++;
            }
        }
        result = Math.max(result, count);
        return result;
    }
}

C++

class Solution {
public:
    int findMaxConsecutiveOnes(vector<int> &nums) {
        int result = 0;
        int count = 0;
        for (auto num : nums) {
            if (num == 0) {
                result = max(result, count);
                count = 0;
            } else {
                count++;
            }
        }
        result = max(result, count);
        return result;
    }
};