题目
标题和出处
标题:重塑矩阵
出处:566. 重塑矩阵
难度
2 级
题目描述
要求
在 MATLAB 中,有一个非常有用的函数 reshape \texttt{reshape} reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。
给出一个 m × n \texttt{m} \times \texttt{n} m×n 的矩阵 mat \texttt{mat} mat,以及两个正整数 r \texttt{r} r 和 c \texttt{c} c,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
如果具有给定参数的 reshape \texttt{reshape} reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
示例
示例 1:
输入:
mat
=
[[1,2],[3,4]],
r
=
1,
c
=
4
\texttt{mat = [[1,2],[3,4]], r = 1, c = 4}
mat = [[1,2],[3,4]], r = 1, c = 4
输出:
[[1,2,3,4]]
\texttt{[[1,2,3,4]]}
[[1,2,3,4]]
示例 2:
输入:
mat
=
[[1,2],[3,4]],
r
=
2,
c
=
4
\texttt{mat = [[1,2],[3,4]], r = 2, c = 4}
mat = [[1,2],[3,4]], r = 2, c = 4
输出:
[[1,2],[3,4]]
\texttt{[[1,2],[3,4]]}
[[1,2],[3,4]]
数据范围
- m = mat.length \texttt{m} = \texttt{mat.length} m=mat.length
- n = mat[i].length \texttt{n} = \texttt{mat[i].length} n=mat[i].length
- 1 ≤ m, n ≤ 100 \texttt{1} \le \texttt{m, n} \le \texttt{100} 1≤m, n≤100
- -1000 ≤ mat[i][j] ≤ 1000 \texttt{-1000} \le \texttt{mat[i][j]} \le \texttt{1000} -1000≤mat[i][j]≤1000
- 1 ≤ r, c ≤ 300 \texttt{1} \le \texttt{r, c} \le \texttt{300} 1≤r, c≤300
解法
思路和算法
在重塑矩阵之前,首先需要判断原矩阵是否可以重塑成新矩阵。重塑操作可行,等价于原矩阵和新矩阵的元素个数相同。根据原矩阵的行数和列数得到原矩阵的元素个数,根据给定的新矩阵的行数和列数得到新矩阵的元素个数,即可判断是否相等。如果不相等,则重塑操作不可行,返回原矩阵。
当重塑操作可行时,将原矩阵的元素依次赋值到新矩阵的对应位置。具体做法是,用 total \textit{total} total 表示矩阵的元素个数,矩阵中的元素下标范围是 [ 0 , total − 1 ] [0, \textit{total}-1] [0,total−1]。遍历每个下标,得到下标对应的原矩阵中的行下标和列下标,以及新矩阵中的行下标和列下标,进行赋值。
代码
class Solution {
public int[][] matrixReshape(int[][] mat, int r, int c) {
int m = mat.length, n = mat[0].length;
if (m * n != r * c) {
return mat;
}
int[][] reshape = new int[r][c];
int total = m * n;
for (int i = 0; i < total; i++) {
int originalRow = i / n, originalColumn = i % n;
int currentRow = i / c, currentColumn = i % c;
reshape[currentRow][currentColumn] = mat[originalRow][originalColumn];
}
return reshape;
}
}
复杂度分析
-
时间复杂度: O ( m n ) O(mn) O(mn),其中 m m m 和 n n n 分别是矩阵 mat \textit{mat} mat 的行数和列数。需要遍历原矩阵中的每个元素,对新矩阵赋值,元素个数即为 m n mn mn。
-
空间复杂度: O ( 1 ) O(1) O(1)。除了返回值以外,使用的空间复杂度是常数。