[LeetCode][Python]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

思路:

把list通过map函数转为相应的字符串list,然后使用"".join()函数连成一个字符串,问题转为,通过"0" split之后最长的子字符串的长度。

    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return len(max("".join(map(str, nums)).split("0")))

别人解法思路:

设置两个计数器:结果值和计数值。以此访问list,如果值为1,计数值加一,结果值取结果值和计数值中的大值。如果值为0,计数值复为0。

    def findMaxConsecutiveOnes2(self, nums):
        result = 0
        count = 0

        for i in range(len(nums)):
            if nums[i] == 1:
                count += 1
                result = max(count, result)
            else:
                count = 0
        return result
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,860评论 18 139
  • 首页 资讯 文章 资源 小组 相亲 登录 注册 首页 最新文章 IT 职场 前端 后端 移动端 数据库 运维 其他...
    Helen_Cat阅读 3,919评论 1 10
  • 楼台不见明月现,几多空思付流年? 才知已是独人在,卸了旧事亦无怜? 君莫说我薄情客,且看众家谁留眷? 但使一位有言...
    木土有阿杜阅读 477评论 0 1
  • 古典的一些事情 今天咱来说说关于古典的一些事情。 先引用一下定义,古典这个定义就是:以一种严肃考究,并...
    烟老师阅读 297评论 0 1