题目要求
Given a binary array, find the maximum number of consecutive 1s in this array.
题目分析及思路
给定一个01数组,要求找到这个数组中连续1的最大长度。可以考虑0的位置,结合数组切片,循环进行。要记得把最后数组的长度加上。
python代码
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
if len(set(nums)) == 1 and nums[0] == 1:
return len(nums)
ones = []
while 0 in nums:
zero = nums.index(0)
ones.append(zero)
nums = nums[zero+1:]
ones.append(len(nums))
return max(ones)