在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()方法(刪除並返回隊頭元素)。