leetcode 485. Max Consecutive Ones( Python )

635 阅读21分钟

描述

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 就更新一次最大个数 result,直到最后遍历完所有元素。

解答

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

运行结果

Runtime: 332 ms, faster than 60.54% of Python online submissions for Max Consecutive Ones.
Memory Usage: 12 MB, less than 36.29% of Python online submissions for Max Consecutive Ones.	

每日格言:每个人都有属于自己的一片森林,迷失的人迷失了,相逢的人会再相逢。

感谢支持 支付宝

支付宝

微信

微信