Array篇easy难度之矩阵对角线元素相加

题目描述

https://leetcode.com/problems/matrix-diagonal-sum/

博主提交的代码

class Solution {
    public int diagonalSum(int[][] c) {
        int currentOffSet  = -1;
        int result = 0;
        for(int i = 0; i < c.length; i++){
            if( isOdd( c.length) && i == c.length / 2 ){
                result+=c[i][i];
            } else{
                result+=c[i][i];
                result+=c[c.length-i - 1][i];
            }
        }
        return result;
        
    }
    public boolean isOdd(int input){
        if ( (input & 1) == 1){
            return true;
        } else {
            return false;
        }
    }
}

他人优秀的代码

https://leetcode.com/problems/matrix-diagonal-sum/discuss/830726/Java-O(n)
我个人不喜欢对于重复相加中心点后,再做减法的解法,那样理解不直观,提前判断不重复加更加直观一些

public int diagonalSum(int[][] mat) {
        int n = mat.length, res = 0;
        for (int i = 0; i < n; i++) {
            res += mat[i][i];
            if (i != n - 1 - i) res += mat[i][n - 1 - i];
        }
        return res;
    }

你可能感兴趣的:(Array篇easy难度之矩阵对角线元素相加)