[LeetCode][Python]485. Max Consecutive Ones

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

Input: [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s.
    The maximum number of consecutive 1s is 3.

Note:

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

思路:

把list通过map函数转为相应的字符串list,然后使用””.join()函数连成一个字符串,问题转为,通过”0″ split之后最长的子字符串的长度。

    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return len(max("".join(map(str, nums)).split("0")))

别人解法思路:

设置两个计数器:结果值和计数值。以此访问list,如果值为1,计数值加一,结果值取结果值和计数值中的大值。如果值为0,计数值复为0。

    def findMaxConsecutiveOnes2(self, nums):
        result = 0
        count = 0

        for i in range(len(nums)):
            if nums[i] == 1:
                count += 1
                result = max(count, result)
            else:
                count = 0
        return result
    原文作者:bluescorpio
    原文地址: https://www.jianshu.com/p/4528e58a772a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞