1. 程式人生 > 其它 >leetcode 485. Max Consecutive Ones(python)

leetcode 485. Max Consecutive Ones(python)

技術標籤:leetcodeleetcode

描述

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.	

每日格言:每個人都有屬於自己的一片森林,迷失的人迷失了,相逢的人會再相逢。