Java解决矩阵对角线元素的和问题

Java解决矩阵对角线元素的和问题

01 题目

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

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

示例 1:

输入: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

02 知识点

  • 二维数组

03 我的题解

java 复制代码
public class shuzu04 {
	public static void main(String[] args) {
		int[][] mat=new int[][] {{1,2,3},
		                          {4,5,6},
		                          {7,8,9}};
		                          System.out.println(diagonalSum(mat));
		                          
		
}
public static int diagonalSum(int[][] mat) {
	int m=mat[0].length;
	 int count=0;
	 for (int i = 0; i < m; i++) {
		count+=mat[i][i];
		count+=mat[i][m-1-i];
	}
	 if (m%2==1) {
		int n=(m-1)/2;
		count-=mat[n][n];
	}
	 return count;
    }
}
相关推荐
二两小咸鱼儿1 小时前
Java Demo - JUnit :Unit Test(Assert Methods)
java·后端·junit
字节源流1 小时前
【spring】配置类和整合Junit
java·后端·spring
跪在镜子前喊帅2 小时前
【面试】Java 多线程
java·面试
PfCoder2 小时前
C#的判断语句总结
开发语言·c#·visual studio·winform
好看资源平台2 小时前
Java/Kotlin逆向基础与Smali语法精解
java·开发语言·kotlin
zimoyin2 小时前
解决 Java/Kotlin 资源加载问题
java·python·kotlin
wjcroom2 小时前
数字投屏叫号器-发射端python窗口定制
开发语言·python
静候光阴2 小时前
python使用venv命令创建虚拟环境(ubuntu22)
linux·开发语言·python
安忘2 小时前
LeetCode 热题 -189. 轮转数组
算法·leetcode·职场和发展
Y1nhl3 小时前
力扣hot100_二叉树(4)_python版本
开发语言·pytorch·python·算法·leetcode·机器学习