566. Reshaping the Matrix
In MATLAB, there is a very useful function reshape
, which can reshape a matrix into another new matrix with a different size, but retain its original data.
A matrix representation is given by two-dimensional array, and two positive integers r
and c
each represents the number of rows desired number of matrix columns and reconstructed.
The reconstructed matrix needs to fill all the elements of the original matrix in the same row traversal order.
If a given parameter of reshape
the operation is feasible and reasonable, new output matrix remodeling; otherwise, the output of the original matrix.
Example 1:
输入:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
输出:
[[1,2,3,4]]
解释:
行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用之前的元素值一行一行填充新矩阵。
Example 2:
输入:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
输出:
[[1,2],
[3,4]]
解释:
没有办法将 2 * 2 矩阵转化为 2 * 4 矩阵。 所以输出原矩阵。
note:
- The width and height of a given matrix are in the range of [1, 100].
- The given r and c are both positive numbers.
method one:
Problem-solving ideas
Simple questions, directly on the code
Reference Code
public int[][] matrixReshape(int[][] nums, int r, int c) {
int R = nums.length, C = nums[0].length;
if (R * C != r * c || (R == r && C == c)) {
return nums;
}
int[][] ans = new int[r][c];
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
int idx = i * C + j;
ans[idx / c][idx % c] = nums[i][j];
}
}
return ans;
}
Results of the