class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
// 首先判断reshape操作数是否可行合理,通过两者间的元素个数是否相等判断
int countPre = nums.length * nums[0].length; // 原矩阵的元素个数
int countPost = r * c; // 重塑矩阵的元素个数
// 判断合理性
// 不合理
if(countPre != countPost) return nums;
// 合理,开始重塑
// 初始化一个二维数组
int[][] resultArr = new int[r][c];
// 定义标志位,判断二维数组中行和列是否填满
int rowIndex = 0;
int colIndex = 0;
// 对原数组进行行遍历,再resultArr中添加元素
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums[0].length; j++){
if(colIndex < c){
// 一行未满,继续添加
resultArr[rowIndex][colIndex] = nums[i][j];
// 列标志位 + 1
colIndex ++;
}
if(colIndex == c){
// 一行已满,行标志位 + 1
rowIndex++;
// 列标志位清零
colIndex = 0;
}
}
}
return resultArr;
}
}
第二种方法,参考题解的映射
class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int m = nums.length;
int n = nums[0].length;
if (m * n != r * c) {
return nums;
}
int[][] ans = new int[r][c];
for (int x = 0; x < m * n; ++x) {
ans[x / c][x % c] = nums[x / n][x % n];
}
return ans;
}
}