In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive integersrandcrepresenting therownumber and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
Example 1:
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.
没啥说的
class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
if(nums == null || nums.length == 0 || nums[0] == null || nums[0].length == 0)
return nums;
int m = nums.length;
int n = nums[0].length;
if(m * n != r * c)
return nums;
int[][] res = new int[r][c];
for(int i = 0; i < m * n; i++) {
int row = i / n;
int col = i % n;
int newRow = i / c;
int newCol = i % c;
res[newRow][newCol] = nums[row][col];
}
return res;
}
}