leetcode 485 最大连续1的个数

直接写,维护最大个数,贪心思想。一种方式是 times 增加的时候和最大个数比较,进行维护;还有一种方式是 times 复位(清零)的时候进行比较,要思考最后一次如果零不出现。

第一种方式:

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        answer = 0
        times = 0
        for num in nums:
            if num == 1:
                times += 1
                answer = max(answer, times)
            else:
                times = 0
        return answer

第二种方式:

class Solution(object):
    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        answer = 0
        times = 0
        for num in nums:
            if num == 1:
                times += 1
            else:
                answer = max(answer, times)                
                times = 0
        answer = max(answer, times)        
        return answer

你可能感兴趣的:(leetcode 485 最大连续1的个数)