给定一个二进制数组, 计算其中最大连续1的个数。
示例 1:
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意:
输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。
解答:
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m = 0
if 1 in nums[:]:
maxC = 1
else:
maxC = 0
for i in range(len(nums)):
if nums[i] == 1:
m += 1
if m > maxC:
maxC = m
else:
if m > maxC:
maxC = m
m = 0
return maxC
别人的解答:(执行用时为 48 ms 的范例)
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxnum=count=0
for num in nums:
if num==1:
count=count+1
else:
if count > maxnum:
maxnum=count
count=0
return max(maxnum,count)