美文网首页
LeetCode之Matrix Diagonal Sum(Kot

LeetCode之Matrix Diagonal Sum(Kot

作者: 糕冷羊 | 来源:发表于2021-02-04 13:29 被阅读0次

    问题:



    方法:
    先遍历主轴,再遍历次轴,然后判断是否有重叠的位置,然后删除重叠的位置,判断条件是列数是否为奇数。

    class MatrixDiagonalSum {
        fun diagonalSum(mat: Array<IntArray>): Int {
            var sum = 0
            for (index in mat[0].indices) {
                sum += mat[index][index]
            }
            for (index in mat[0].lastIndex downTo 0) {
                sum += mat[index][mat.lastIndex - index]
            }
            if (mat[0].size % 2 != 0) {
                sum -= mat[mat[0].lastIndex / 2][mat[0].lastIndex / 2]
            }
            return sum
        }
    }
    

    有问题随时沟通

    具体代码实现可以参考Github

    相关文章

      网友评论

          本文标题:LeetCode之Matrix Diagonal Sum(Kot

          本文链接:https://www.haomeiwen.com/subject/tvdbtltx.html