原题:
给你一个由二维数组
mat
表示的m x n
矩阵,以及两个正整数r
和c
,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。
如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
解题思路
设为 r e s u l t [ r ] [ c ] result[r][c] result[r][c] 要返回的值,对于 r e s u l t result result 中每个元素遍历并赋值,注意处理原数组中脚标的变化即可。
代码
class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int m = mat.length;
int n = mat[0].length;
int i,j;
int[][] result = new int[r][c];
int k = 0,l = 0;
if(m*n != r*c) return mat;
for(i = 0;i < r; i++){
for(j = 0;j < c; j++,l++){
if(l == n){
l = 0;
k++;
}
result[i][j] = mat[k][l];
}
}
return result;
}
}