在MATLAB中,有一个非常有用的功能称为“重塑”,可以重塑一个矩阵与不同大小的一个新的但保持其原始数据。
给你一个矩阵表示为一个二维数组,和两个正整数r和c代表希望重塑的行数和列数矩阵,分别。
重塑矩阵需要充满原始矩阵的所有元素在同一个row-traversing顺序。
如果给出的“重塑”操作参数是可能的,合法的,输出新的重塑矩阵;否则,输出原始矩阵。
Example1
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example2
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
public int[][] matrixReshape(int[][] nums, int r, int c) {
int n = nums.length, m = nums[0].length;
if (r*c != n*m) return nums;
int[][] res = new int[r][c];
for (int i=0;i<r*c;i++)
res[i/c][i%c] = nums[i/m][i%m];
return res;
}
res[i/c][i%c]=nums[i/m][i%m];
或者可以先创建一个Queue,把数组元素先 存放进去,后用Queue.remove()方法(删除并返回队头元素)。