[LeetCode]Max Consecutive Ones

题目描述:

LeetCode 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

题目大意:

给定一个二进制数组,计算数组中出现的最大连续1的个数。

注意:

  • 输入数组只包含0和1
  • 数组长度是正整数并且不会超过10000

解题思路:

一趟遍历+计数器

Python代码:

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

 

本文链接:http://bookshadow.com/weblog/2017/01/15/leetcode-max-consecutive-ones/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论