Leetcode 1572) Matrix Diagonal Sum

image

class Solution {
    public int diagonalSum(int[][] mat) {
        int sum = 0;
        for(int i=0;i<mat.length;i++){
            sum+=mat[i][i];
            sum+=mat[i][mat.length-i-1];
        }
        int mid = mat.length/2;
        int mod = mat.length%2;
        if(mod!=0){
            sum-=mat[mid][mid];
        }
        return sum;

    }
}

다른 답안

class Solution {
    public int diagonalSum(int[][] mat) {
        int leftX = 0; 
        int leftY = 0; 
        int rightX = mat[0].length - 1; 
        int rightY = 0;
        int sum = 0;
        while(leftX < mat[0].length && leftY < mat[0].length && 
              rightX >= 0 && rightY < mat[0].length
             ){
            sum += mat[leftX][leftY];
            sum += mat[rightY][rightX];
            leftX++;
            leftY++;
            rightX--;
            rightY++;
        }
        return sum - (mat.length % 2 != 0 ? mat[mat.length/ 2][mat[0].length / 2] : 0);
    }
}

© 2018. All rights reserved.

Powered by Hydejack v8.5.2