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 integers r and c representing the row number 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.
Example 2:
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.
这道题是LeetCode上的一道简单的数组题,主要是对矩阵(matrix )进行变换,若输入的行和列都合法的话,就转换为该矩阵,若不合法就返回原来的矩阵。题意不难理解,思路也很清晰。
第一步:先根据两个矩阵的元素个数是否相等来判断我们拿到的r(行)和c(列)是否合法,若不合法,那么直接返回原矩阵;
第二步:把原矩阵的元素抽取出来放入目标矩阵中
这种思路比较符合大众思维
那么直接撸代码
public int[][] matrixReshape(int[][] nums, int r, int c) {
if (nums.length*nums[0].length != r*c){
return nums;
}
int target_matrix[][] = new int[r][c];
int listNums[] = new int[nums.length*nums[0].length];
int n = 0;
for (int i = 0;i < nums.length;i++){
for (int j = 0;j < nums[0].length;j++){
listNums[n] = nums[i][j];
n++;
}
}
n = 0;
for (int i = 0;i < r;i++){
for (int j = 0;j < c;j++){
target_matrix[i][j]=listNums[n];
n++;
}
}
return target_matrix;
}
第一种方法好理解但过于麻烦,因为我们需要把原矩阵的元素抽取出来然后在进行重塑,有没有一步到位的方法呢?当然有!
接下来讲解第二种方法
第一步:同第一种方法,判断r与c是否合法
第二步:我们重新定义一个行和列,在遍历原矩阵的同时把元素放入目标矩阵,同时判断 当前元素所在列若大于等于 目标矩阵的列,就把行号+1,列号清零
看代码
public int[][] optimumSolution(int[][] nums,int r,int c) {
if(r == 0 || c == 0){
return nums;
}
if((r * c) != (nums.length * nums[0].length)){
return nums;
}
int[][] arr = new int[r][c];
int row = 0, col = 0;
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums[i].length; j++){
arr[row][col++] = nums[i][j];
if(col >= c){
row++;
col = 0;
}
}
}
return arr;
}