在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据。
给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。
如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
考察:数组,矩阵
class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int m = mat.length; //横着的长度
int n = mat[0].length; //竖着的长度
if (m * n != r * c) { //如果两个相乘不相等,则两个数组容量不同,不能重塑
return mat;
}
int[][] ans = new int[r][c];
for (int x = 0; x < m * n; ++x) {
ans[x / c][x % c] = mat[x / n][x % n];
//对于 x∈[0,mn)x \in [0, mn)x∈[0,mn),第 xxx 个元素在 nums\textit{nums}nums 中对应的下标为 (x / n,x % n)(x ~/~ n, x~\%~ n)(x / n,x % n),而在新的重塑矩阵中对应的下标为 (x / c,x % c)(x ~/~ c, x~\%~ c)(x / c,x % c)
}
return ans;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reshape-the-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。