Skip to main content

Leetcode 1572

· One min read
Junhe Chen

working with matrix can be difficult lets start this easy question tho.

class Solution {
public int diagonalSum(int[][] mat) {
int res = 0;
int n = mat.length, m = mat[0].length;
int row = 0, col_primary = 0, col_secondary = m - 1;
while(row < n){
res += mat[row][col_primary];
res += mat[row][col_secondary];
if(col_primary == col_secondary){
res -= mat[row][col_primary];
}
row ++;
col_primary ++;
col_secondary --;
}
return res;

}

}

weekly challenge, simply mimic the matrix multiplication prune out 0s

class Solution {
public int[][] multiply(int[][] mat1, int[][] mat2) {
int n = mat1.length;
int k = mat1[0].length;
int m = mat2[0].length;
int[][] res = new int[n][m];

for(int rowIndex = 0; rowIndex < n; rowIndex ++){
for(int elementIndex = 0; elementIndex < k; elementIndex++){
if(mat1[rowIndex][elementIndex] != 0){
// if just 0 we dont have to calculate it just gonna be 0
for(int colIndex = 0; colIndex < m; colIndex++){
res[rowIndex][colIndex] += mat1[rowIndex][elementIndex] * mat2[elementIndex][colIndex];
}
}
}
}
return res;

}
}