carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1572:矩阵对角线元素的和(matrix-diagonal-sum) #247

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个正方形矩阵 mat,请你返回矩阵对角线元素的和。

请你返回在矩阵主对角线上的元素和副对角线上且不在主对角线上元素的和。

 

示例  1:

image

输入:mat = [[1,2,3],   [4,5,6],   [7,8,9]] 输出:25 解释:对角线的和为:1 + 5 + 9 + 3 + 7 = 25 请注意,元素 mat[1][1] = 5 只会被计算一次。

示例  2:

输入:mat = [[1,1,1,1],   [1,1,1,1],   [1,1,1,1],   [1,1,1,1]] 输出:8

示例 3:

输入:mat = [[5]] 输出:5  

提示:

n == mat.length == mat[i].length 1 <= n <= 100 1 <= mat[i][j] <= 100

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/matrix-diagonal-sum

carloscn commented 1 year ago

问题分析

pub fn diagonal_sum(mat: Vec<Vec<i32>>) -> i32
{
    if mat.is_empty() || mat.len() != mat[0].len() {
        return 0;
    }

    let mut ret:i32 = 0;

    for i in 0..mat.len() {
        ret += mat[i][i];
        ret += mat[i][mat.len() - i - 1];
        if (i & 0x1 == 1) &&
           (mat.len() / 2) as i32 == i as i32 {
            ret -= mat[i][i];
        }
    }

    return ret;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/555303 https://github.com/carloscn/structstudy/commit/bd2204d8bfc1ddd9118086949b747a6c7e147c01