Max Consecutive Ones,LeetCode,485

好的,我们来详细讲解一下 LeetCode 上的第 485 题:Max Consecutive Ones(最大连续1的个数)。

题目描述

给定一个二进制数组,返回该数组中连续1的最大个数。

示例 1:

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

解题思路

这个问题可以通过一次遍历数组来解决。我们可以使用两个变量:

  1. max_count:用来记录最大的连续1的个数。
  2. current_count:用来记录当前连续1的个数。

遍历数组时,如果遇到1,就将current_count加1;如果遇到0,就将current_count重置为0,并将max_count更新为current_countmax_count中的较大值。

具体步骤

  1. 初始化max_countcurrent_count为0。
  2. 遍历数组中的每一个元素:
    • 如果元素为1,current_count加1。
    • 如果元素为0,比较current_countmax_count,更新max_count为较大值,然后将current_count重置为0。
  3. 遍历结束后,再次比较current_countmax_count,以确保最后一个连续1的序列被考虑进去。
  4. 返回max_count

代码实现

以下是使用Python实现的代码:

class Solution: def findMaxConsecutiveOnes(self, nums): max_count = 0 current_count = 0

    for num in nums:
        if num == 1:
            current_count += 1
        else:
            max_count = max(max_count, current_count)
            current_count = 0

    # 最后一次检查,以防数组以连续1结尾
    max_count = max(max_count, current_count)

    return max_count

复杂度分析

  • 时间复杂度: O(n),其中n是数组的长度。我们只需要遍历一次数组。
  • 空间复杂度: O(1),我们只使用了常数个额外空间。

测试用例

sol = Solution() print(sol.findMaxConsecutiveOnes([1,1,0,1,1,1])) # 输出: 3 print(sol.findMaxConsecutiveOnes([1,0,1,1,0,1])) # 输出: 2 print(sol.findMaxConsecutiveOnes([0,0,0,0,0,0])) # 输出: 0 print(sol.findMaxConsecutiveOnes([1,1,1,1,1,1])) # 输出: 6

通过这些测试用例,我们可以验证代码的正确性。

希望这个详细的解答对你有帮助!如果有其他问题,欢迎继续提问。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注