给定一个二进制数组, 计算其中最大连续1的个数。
示例 :
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意:
输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。
思路:
设置两个变量max和count,一个用于保存最大长度,一个用于保存当前长度。遍历列表,遇1则count加1,立即检查是否超过max,若是则更新max;遇0则重置count.
代码:
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max=0
count=0
for x in nums:
if x==1:
count+=1
if count>max:
max=count
else:
count=0
return max
参考:
无