485. 最大连续1的个数

https://leetcode-cn.com/problems/max-consecutive-ones/

解法一:

思路:用一个累加器count,一旦遇到0就清零,否则就+1.用maxCount记录下count的最大值,即可知道序列中最长的连续1有多少.

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

解法二:py专属

虽然慢,但是简洁。将nums转成01串,然后按0切分,求最长的1子串

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        return max(len(l) for l in ''.join([str(num) for num in nums]).split('0'))

最后更新于