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

二维数组对角线求和函数调试及替代实现方案咨询

二维数组对角线求和的正确实现逻辑

你的代码无法通过测试用例,核心问题是当数组为奇数阶方阵时,两条对角线的交点元素会被重复计算。比如3×3数组的中间元素,在循环到i=1时,arr[i][i]和arr[i][length-i]指向同一个元素,导致总和多算了一次该值。

下面是几种可行的修正/实现方案:

修正版循环实现

这是在你原有逻辑基础上的优化,通过判断避免重复累加:

const diagonalSum = function(arr) {
    const n = arr.length;
    let sum = 0;
    for (let i = 0; i < n; i++) {
        // 累加主对角线元素
        sum += arr[i][i];
        // 副对角线元素与主对角线不重合时才累加
        const oppositeIndex = n - 1 - i;
        if (i !== oppositeIndex) {
            sum += arr[i][oppositeIndex];
        }
    }
    return sum;
};

分开遍历两条对角线

将主、副对角线的遍历分开处理,逻辑更清晰:

const diagonalSum = function(arr) {
    const n = arr.length;
    let sum = 0;
    // 遍历主对角线:行号等于列号
    for (let i = 0; i < n; i++) {
        sum += arr[i][i];
    }
    // 遍历副对角线:行号+列号 = n-1,跳过重复元素
    for (let i = 0; i < n; i++) {
        const j = n - 1 - i;
        if (i !== j) {
            sum += arr[i][j];
        }
    }
    return sum;
};

简洁版:使用reduce方法

利用数组的reduce方法实现更紧凑的代码:

const diagonalSum = function(arr) {
    const n = arr.length;
    return arr.reduce((total, row, index) => {
        const opposite = n - 1 - index;
        return total + row[index] + (index !== opposite ? row[opposite] : 0);
    }, 0);
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:00:33