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

检测二进制数组中是否仅存在一组连续1的函数实现需求

判断数组是否仅含一组连续1

问题需求

给定一个仅包含0和1的数组,实现一个函数:当数组仅存在一组连续的1,且该组之外无其他1时返回true,否则返回false。

测试用例

  • [0, 0, 1, 1, 0, 0] → true
  • [1, 0, 1, 0, 0, 0] → false
  • [1, 0, 1, 1, 0, 0] → false
  • [1, 1, 0, 1, 1, 0] → false
  • [0, 1, 1, 1, 1, 0] → true
  • [0, 0, 1, 1, 1, 1] → true

解法思路

核心逻辑是统计数组中连续1的组数:

  1. 遍历数组,用变量标记当前是否处于连续1的区间内
  2. 每当从0切换到1时,代表新的连续1组开始,组数加1
  3. 若组数超过1,直接返回false(已满足失败条件)
  4. 遍历结束后,仅当组数恰好为1时返回true

代码实现

Python 版本

def has_single_consecutive_ones(arr):
    consecutive_groups = 0
    in_group = False
    for num in arr:
        if num == 1:
            if not in_group:
                consecutive_groups += 1
                if consecutive_groups > 1:
                    return False
                in_group = True
        else:
            in_group = False
    return consecutive_groups == 1

JavaScript 版本

function hasSingleConsecutiveOnes(arr) {
    let consecutiveGroups = 0;
    let inGroup = false;
    for (const num of arr) {
        if (num === 1) {
            if (!inGroup) {
                consecutiveGroups++;
                if (consecutiveGroups > 1) return false;
                inGroup = true;
            }
        } else {
            inGroup = false;
        }
    }
    return consecutiveGroups === 1;
}

额外测试场景

  • 全0数组 [0,0,0] → 返回false(无连续1组)
  • 全1数组 [1,1,1] → 返回true(仅一组连续1)

内容的提问来源于stack exchange,提问作者Lelouch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:15:39