566. 重塑矩阵
题目描述
解题思路
- 首先判断输入是否合法,即 r * c是否等于 mat.length * mat[0].length,如果不等直接返回mat;
- 使用两个整数 h 和w,分别表示结果数组的高(行)和宽(列),初始时 h 和w均为0;
- 遍历mat数组,每遍历一个元素将其存入结果数组中,并将w + 1,当w == c时,将h + 1,以及w置为0。直至遍历结束,得到转换后的矩阵。
代码实现
class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
// 判断给定参数的 reshape 操作是否是可行且合理的
if(r*c != mat.length*mat[0].length){
return mat;
}
int[][] res = new int[r][c];
// 分别表示结果数组的高(行)和宽(列)
int h = 0,w = 0;
for(int i=0;i<mat.length;i++){
for(int j=0;j<mat[i].length;j++){
res[h][w] = mat[i][j]; // 遍历元素将其存入res
++w; // 宽+1
if(w == c){
++h; //高+1
w = 0; //宽置为0
}
}
}
return res;
}
}