思路:
1、处理好len(nums) < 2时的情形;
2、用指针i遍历nums,用ans[]存放每一串连续1的长度,用计数器count记录:
i指向的是1则计数器加1;
i指向的不是1且前一位是1,则将计数器值添加到ans[]中,并清空计数器;
3、返回max(ans)。
1 class Solution(object): 2 def findMaxConsecutiveOnes(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 count = 1 if nums[0] == 1 else 0 8 ans = [] 9 if len(nums) == 1: 10 ans.append(count) 11 for i in range(1, len(nums)): 12 if nums[i] == 1: 13 count += 1 14 elif nums[i - 1] == 1 and nums[i] != 1: 15 ans.append(count) 16 count = 0 17 if i == len(nums) - 1: 18 ans.append(count) 19 return max(ans) 20 21 22 if __name__ == '__main__': 23 solution = Solution() 24 print(solution.findMaxConsecutiveOnes([1, 1, 0, 1, 1, 1]))