题目:给定一个二进制数组,计算其中最大连续1的个数。
示例1:
输入:[1,1,0,1,1,1]
输出:3
解释:开头的两位和最后的三位都是连续1,所以最大连续1的个数是3
注意:
- 输入的数组只包含0和1
- 输入的数组的长度是正整数,且不超过10000.
思路:因为题目只需求最大连续1的个数,考虑到开头和末尾都有可能为1,所以我们在列表的首尾各自添加1个0,接着遍历一遍数组,记录出现0的索引的数组,最后再遍历一遍新创建的数组,取相邻索引所对应的元素的差再减去1的最大值就是目标值。
class Solution:
def findMaxConsecutiveOnes(self,nums):
"""
:type nums: List[int]
:rtype: int
"""
result_list,max_nums = [],0
new_nums = [0] + nums + [0]
for i in range(len(new_nums)):
if new_nums[i] == 0:
result_list.append(i)
for j in range(1,len(result_list)):
max_num = max(max_num,result_list[j] - result_list[j-1] - 1)
return max_num