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/