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

求助:如何实现数组中非零元素值向前后元素的扩散计算

解决数组阶梯式扩散的问题

我来帮你搞定这个问题!你之前的尝试只考虑了相邻元素的影响,完全没覆盖到所有非零元素对每个位置的作用,还错误地改变了数组长度,这就是结果不符合预期的原因。先明确核心规则:数组中每个位置的最终值,是所有非零元素对它的贡献之和。每个非零元素n在位置j,对位置i的贡献为max(n - 两点间绝对距离, 0)(贡献不能为负数,否则取0)。

实现思路

  1. 先收集原数组里所有非零元素的位置和对应值,方便后续遍历计算每个位置的总贡献;
  2. 遍历原数组的每个位置,对每个位置累加所有非零元素的有效贡献,得到该位置的结果。

正确代码

function spread(balloon) {
    // 收集所有非零元素的位置与对应值
    const nonZeroElements = balloon
        .map((value, index) => value !== 0 ? { value, index } : null)
        .filter(item => item !== null);
    
    // 计算每个位置的总贡献
    return balloon.map((_, currentIndex) => {
        return nonZeroElements.reduce((total, { value, index }) => {
            const distance = Math.abs(currentIndex - index);
            const contribution = Math.max(value - distance, 0);
            return total + contribution;
        }, 0);
    });
}

测试验证

用你提供的测试用例验证,结果完全符合预期:

const array1 = [0, 0, 0, 0, 4, 0, 0, 3, 0];
console.log(spread(array1)); // 输出: [0, 1, 2, 3, 4, 4, 4, 4, 2]

const array2 = [0, 0, 2, 0, 0];
console.log(spread(array2)); // 输出: [0, 1, 2, 1, 0]

// 验证其他示例
console.log(spread([0,0,0,4,0,0,0])); // [1,2,3,4,3,2,1]
console.log(spread([0,0,0,3,0,2,0])); // [0,1,2,3,3,3,1]
console.log(spread([3,0,0,0])); // [3,2,1,0]

这个实现逻辑清晰,既保持了数组长度和原数组一致,又完整覆盖了所有非零元素的影响,完美满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:46:18