-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMatrix diagonal sum.java
More file actions
48 lines (37 loc) · 983 Bytes
/
Matrix diagonal sum.java
File metadata and controls
48 lines (37 loc) · 983 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution {
public int diagonalSum(int[][] mat) {
int sum=0,j=mat.length-1;
for(int i=0;i<mat.length;i++)
{
sum+=mat[i][i]+mat[i][j--];
}
if(mat.length%2==1){
sum-=mat[mat.length/2][mat.length/2];
}
return sum;
}
}
//faster approach
class Solution {
public int diagonalSum(int[][] mat) {
int n = mat.length;
int i = 0;
int j = 0;
int ans = 0;
while(i<n){ // for first digonal
ans += mat[i][j];
i++;
j++;
}
int row = 0;
int col = n - 1;
while(row < n){ // for second digonal
if(row != col){ // this condition is to prevent addition if row and column overlaps
ans+= mat[row][col];
}
row++;
col--;
}
return ans;
}
}