# 矩阵变形 Reshape the Matrix

2017/05/15 22:40

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.```

Note:

1. The height and width of the given matrix is in range [1, 100].
2. The given r and c are all positive.

①需要判断矩阵是否能够正确的进行转换（总数目是否相等），其次难点在于数组的转换，我用了最简单的直接转换。用时13ms

public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int len1 = nums.length;
int len2 = nums[0].length;
if(len1 * len2 != r * c){
return nums;
}
int res[][] = new int[r][c];
int row = 0;
int col = 0;
for(int i = 0; i < len1; i ++){
for(int j = 0; j < len2; j ++){
res[row][col] = nums[i][j];
col ++;
if(col == c){
row ++;
col = 0;
}
}
}
return res;
}
}

②使用队列存储矩阵，此时该矩阵只有一行，更好存储，用时16 ms

public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int len1 = nums.length;
int len2 = nums[0].length;
if (len1 * len2 != r * c) {
return nums;
}
for (int i = 0;i < len1 ;i ++ ) {
for (int j = 0;j < len2 ;j ++ ) {
}
}
int res[][] = new int[r][c];
for (int i = 0;i < r ;i ++ ) {
for (int j = 0;j < c ;j ++ ) {
res[i][j] = queue.remove();
}
}
return res;
}
}

③使用除法和模数，实现比较简单，但是需要深入理解数组的原理。我们想一下二维矩阵存储在一维空间时的存储方法为，nums[i][j]存储在第nums[i*k+j]个位置，其中k表示矩阵的列数，反之，当我们由一维回到二维矩阵时，设数组下标为count，则二维矩阵的显示为nums[count/k,count%k],这样，我们就可以得到对应的矩阵。 用时16ms.

public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int len1 = nums.length;
int len2 = nums[0].length;
if (len1 * len2 != r * c) {
return nums;
}
int res[][] = new int[r][c];
int count = 0;
for (int i = 0;i < len1 ;i ++ ) {
for (int j = 0;j < len2 ;j ++ ) {
res[count / c][count % c] = nums[i][j];
count ++;
}
}
return res;
}
}

public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int len1 = nums.length;//行数
int len2 = nums[0].length;//列数
if(len1 * len2 != r * c){
return nums;
}
int res[][] = new int[r][c];
int count = 0;
for (int i = 0;i < len1 ;i ++ ) {
for (int j = 0;j < len2 ;j ++ ) {
count = i * len2 + j;
res[count / c][count % c] = nums[i][j];
}
}
return res;
}
}

0
0 收藏

0 评论
0 收藏
0