485. 最大連續1的個數

  

思路:

一、處理好len(nums) < 2時的情形;
二、用指針i遍歷nums,用ans[]存放每一串連續1的長度,用計數器count記錄:
i指向的是1則計數器加1;
i指向的不是1且前一位是1,則將計數器值添加到ans[]中,並清空計數器;
三、返回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]))
相關文章
相關標籤/搜索