zoukankan      html  css  js  c++  java
  • 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

    个人解法:(python)

    class Solution(object):
        def findMaxConsecutiveOnes(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            count = 0
            arr_result = []
            for i in range(len(nums)):
                if nums[i] == 1:
                    count += 1
                else:
                    if count != 0:
                        arr_result.append(count)
                    count = 0
                if i == (len(nums)-1) and nums[i] == 1:
                    arr_result.append(count)
            result = 0
            for i in arr_result:
                if i > result:
                    result = i
            return result

    看了别人的解法,思路一样,python中有个比较大小的max函数,忘记用了。

    应该是:

    class Solution(object):
        def findMaxConsecutiveOnes(self, nums):
            cnt = 0
            ans = 0
            for num in nums:
                if num == 1:
                    cnt += 1
                    ans = max(ans, cnt)
                else:
                    cnt = 0
            return ans

    第一遍做,没太考虑最优解,第二遍刷题的时候在考虑。

  • 相关阅读:
    保险精算导论
    天津大学C语言程序设计
    会计学
    WIN10 CH340安装失败
    好用的浏览器插件
    好用的壁纸软件
    30讲 窗口看门狗
    STM32替换Arduino直通车
    stm32系列芯片独立看门狗(IWDG)溢出时间计算原理
    AD 电子元器件图片、名称及符号对照
  • 原文地址:https://www.cnblogs.com/jingtyu/p/7146884.html
Copyright © 2011-2022 走看看