You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计数字数组中被0分隔的chunk块的总数量?

数组chunk数量统计实现方案

核心解决思路是通过状态标记规避连续0的重复计数,不用额外处理连续0的逻辑,单次遍历即可完成统计,时间复杂度O(n),空间复杂度O(1)。

实现逻辑

  • 初始化两个变量:chunk_count(统计chunk总数,初始值0)、in_chunk(标记当前是否处于非零chunk区间内,初始值false)
  • 遍历数组的每一个元素:
    • 若当前元素非0,且in_chunk为false:说明刚进入一个新的非零chunk,chunk_count加1,同时将in_chunk设为true
    • 若当前元素为0,且in_chunk为true:说明刚离开一个非零chunk,将in_chunk设为false
  • 遍历结束后直接返回chunk_count即可

代码示例(Python)

def count_chunks(num_arr):
    chunk_count = 0
    in_chunk = False
    for num in num_arr:
        if num != 0:
            if not in_chunk:
                chunk_count += 1
                in_chunk = True
        else:
            if in_chunk:
                in_chunk = False
    return chunk_count

# 测试官方示例
test_arr = [5, 4, 0, 0, -1, 0, 2, 0, 0]
print(count_chunks(test_arr)) # 输出结果为3

边界情况验证

所有边界场景均可正确处理:

  • 全零数组[0, 0, 0] → 返回0
  • 无零数组[1, -2, 3] → 返回1
  • 开头为零的数组[0, 0, 5, 6, 0] → 返回1
  • 结尾为非零的数组[0, 3, 0, 2, 7] → 返回2

内容的提问来源于stack exchange,提问作者My name is jeff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:24:03