(python版) Leetcode-485. 最大连续1的个数

01 题目

给定一个二进制数组, 计算其中最大连续1的个数。

示例 1:

输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.

注意
输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。

链接:https://leetcode-cn.com/problems/max-consecutive-ones

02 解析&代码一:一次遍历

  • 当我们遇到 1 时,count 加一。
  • 当我们遇到 0 时:
  • 将 count 与 maxCount 比较,maxCoiunt 记录较大值。
    • 将 count 设为 0。
    • 返回 maxCount。

复杂度分析

时间复杂度:O(N)O(N)。NN 值得是数组的长度。
空间复杂度:O(1)O(1),仅仅使用了 count 和 maxCount。

官方代码

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        count = max_count = 0
        for num in nums:
            if num == 1:
                # Increment the count of 1's by one.
                count += 1
            else:
                # Find the maximum till now.
                max_count = max(max_count, count)
                # Reset count of 1.
                count = 0
        return max(max_count, count)

在这里插入图片描述

03 解析&代码二:

  • 在 Python 中可以使用 map 和 join 来解决此问题。
  • 使用 splits 函数在 0 处分割将数组转换成字符串。
  • 在获取子串的最大长度就是最大连续 1 的长度。
def findMaxConsecutiveOnes(self, nums):
  return max(map(len, ''.join(map(str, nums)).split('0')))

这个慢点
在这里插入图片描述
链接:https://leetcode-cn.com/problems/max-consecutive-ones/solution/zui-da-lian-xu-1de-ge-shu-by-leetcode/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值