Skip to content

Latest commit

 

History

History
103 lines (77 loc) · 1.9 KB

File metadata and controls

103 lines (77 loc) · 1.9 KB

English Version

题目描述

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

 

示例:

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

 

提示:

  • 输入的数组只包含 01
  • 输入数组的长度是正整数,且不超过 10,000。

解法

Python3

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        res = t = 0
        for num in nums:
            if num == 1:
                t += 1
            else:
                res = max(res, t)
                t = 0
        return max(res, t)

Java

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

JavaScript

/**
 * @param {number[]} nums
 * @return {number}
 */
var findMaxConsecutiveOnes = function (nums) {
  let res = 0,
    t = 0;
  for (let num of nums) {
    if (num == 1) {
      ++t;
    } else {
      res = Math.max(res, t);
      t = 0;
    }
  }
  return Math.max(res, t);
};

...