给定一个二进制数组, 计算其中最大连续1的个数。
示例 1:
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意:
输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
result = 0
left = 0
right = 0
arrays = []
if len(nums) == 0 or 1 not in nums:
return 0
elif len(nums) == 1 and nums[0] == 1:
return 1
elif len(nums) == 1 and nums[0] == 0:
return 0
for i in range(len(nums)-1):
if nums[i] == 0:
left += 1
right += 1
elif nums[i] == 1 and nums[i+1] == 1:
right += 1
elif nums[i] == 1 and nums[i+1] == 0:
if right-left+1 > result:
result = right-left+1
left = right+1
right = right+1
if nums[-1] == 1 and nums[-2] == 0:
if result == 0:
result = 1
elif nums[-1] == 1 and nums[-2] == 1:
if right-left+1 > result:
result = right-left+1
return result
Andy Wang 发布了147 篇原创文章 · 获赞 14 · 访问量 3万+ 私信 关注