[Leetcode] 485. 最大连续1的个数 Python3

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

示例 1:

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

注意:

  • 输入的数组只包含 01
  • 输入数组的长度是正整数,且不超过 10,000。
class Solution:
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = 0  #计算每一次连续1的个数
        maxCount = 0 #存放最大连续1的个数
        if len(nums) == 1: #nums=[0] 或nums=[1]
            return nums[0]
        for i in range(len(nums)):
            if nums[i] != 1: #当遇到0的时候,count重置为0
                count = 0
            else:           #遇到1
                count += 1
                if maxCount < count:  #把最大值存入maxCount中
                    maxCount = count

        return maxCount
            

猜你喜欢

转载自blog.csdn.net/niceHou666/article/details/81456395