LeetCode—1572

Approach

# 給予一個方形矩陣mat,回傳該矩陣對角線的和。
Given a square matrix mat, return the sum of the matrix diagonals.

# 奇數大小矩陣的最中央的元素會被加兩次,要多扣掉一次
For matrices with an odd size, the center element is added twice and needs to be subtracted once.

Time Complexity

# n = length of vector(Row or Column)
O(n)

Space Complexity

# n = length of vector
O(n*n)

Code

class Solution {
public:
    int diagonalSum(vector<vector<int>>& mat) {
        int r = mat.size(), sum = 0;
        
        for (int i = 0 ; i < r ; i++) {
            sum += mat[i][i];
            sum += mat[i][r - i - 1];
        }

        if (r % 2 == 1) {
            sum -= mat[r/2][r/2];
        }

        return sum;
    }
};