add: 230508

This commit is contained in:
Eatswap 2023-05-08 12:40:29 +08:00
parent d4b780b2f0
commit 6471f95007
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 26 additions and 0 deletions

21
cpp/2305/LC230508.cpp Normal file
View File

@ -0,0 +1,21 @@
#include <vector>
/**
* 1572. Matrix Diagonal Sum
*
* 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.
*/
class LC230508 {
public:
static int diagonalSum(const std::vector<std::vector<int>>&) noexcept;
};
int LC230508::diagonalSum(const std::vector<std::vector<int>>& mat) noexcept {
const int n = mat.size();
int ret = 0;
for (int i = 0; i < n; ++i)
ret += mat[i][i] + mat[i][n - 1 - i];
return ret - (n & 1 ? mat[n >> 1][n >> 1] : 0);
}

View File

@ -75,4 +75,9 @@ public:
static std::vector<int> longestObstacleCourseAtEachPosition(const std::vector<int>&) noexcept; static std::vector<int> longestObstacleCourseAtEachPosition(const std::vector<int>&) noexcept;
}; };
class LC230508 {
public:
static int diagonalSum(const std::vector<std::vector<int>>&) noexcept;
};
#endif //LEETCODE_CPP_DEFS_H #endif //LEETCODE_CPP_DEFS_H