LeetCode知识点总结 - 1572

该博客介绍了LeetCode第1572题的解决方案,题目要求计算一个方阵中主对角线和副对角线(非主对角线)元素的和。提供的Java代码实现通过遍历矩阵并累加对角线元素来求解,对于奇数大小的矩阵会减去中间元素以避免重复计数。
摘要由CSDN通过智能技术生成

LeetCode 1572. Matrix Diagonal Sum

考点难度
MatrixEasy
题目

Given a square matrix mat, return the sum of the matrix diagonals.

Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal.

思路

先把两条对角线的数加起来,如果matrix的边长是奇数说明有一个重复。

答案
public int diagonalSum(int[][] mat) {
        int res = 0;
        int n = mat.length;
        for (int i=0; i<n; i++) {
            res += mat[i][i]; 
            res += mat[n-1-i][i]; 
        }
        return n % 2 == 0 ? res : res - mat[n/2][n/2]; 
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值