【LeeCode 简单 数组 python3】485.最大连续1的个数

想要看更加舒服的排版、更加准时的推送
关注公众号“不太灵光的程序员”
每日八点有干货推送,微信随时解答你的疑问

485.最大连续1的个数 python3

简单 数组

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

示例 1:

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

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

from typing import List


# 56%
# 执行用时:448 ms
# 内存消耗:13.7 MB
class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        if not nums: return 0
        i = 0
        j = 1
        n = len(nums)
        big_num = num = nums[0]
        while i < n and j < n:
            if nums[j] == 1:
                num += 1
                i = j
            else:
                num = 0
                i = j
            if num > big_num:
                big_num = num
            j += 1
        return big_num


s = Solution()
nums = [0, 0]
ret = s.findMaxConsecutiveOnes(nums)
print(ret, ret == 0)
nums = [0, 1]
ret = s.findMaxConsecutiveOnes(nums)
print(ret, ret == 1)
nums = [1]
ret = s.findMaxConsecutiveOnes(nums)
print(ret, ret == 1)
nums = [1, 0, 1, 1, 0, 1]
ret = s.findMaxConsecutiveOnes(nums)
print(ret, ret == 2)

猜你喜欢

转载自blog.csdn.net/qq_23934063/article/details/107579445
今日推荐