(Leetcode)Max Consecutive Ones --- 寻找最长连接数

来源:互联网 发布:it's skin 编辑:程序博客网 时间:2024/06/08 18:55

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

Example 1:

Input: [1,1,0,1,1,1]Output: 3Explanation: 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

Subscribe to see which companies asked this question.


解题分析:

首先对于这个题目我们只需要考虑两点情况

1.101010010101100111101这种情况

2.11111111111111111111111全是1的情况

我们可以定义两个变量,count计数器,max返回值来处理如下逻辑

首先,当前元素是1的话,我们只需要将计数器count加一,若当前元素是0的话,则先判断max是不是小于count,如果小于的话,就将max = count,

否则不做操作。

然后最后避免出现全是1的情况,我们可以加一组判断。



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


0 0