您的位置:首页 > 其它

Leetcode 566 Reshape the Matrix 将数组转换为我们想要的行和列

2017-10-27 10:51 429 查看
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:

The height and width of the given matrix is in range [1, 100].

The given r and c are all positive.

思路分析:

其实这个题非常的简单,

1.首先我们排除转换的情况,接下来呢,

2.我们创建新的数组来返回结果,行列赋值为我们想要的大小。

3.遍历被转换的数组,此时维护两个变量,新的行和列,如果未达到我们要转的列,则列一直加,直到达到我们需要的列的大小,然后行加,开始下一行的遍历赋值。

代码如下:

public static int[][] matrixReshape(int[][] nums, int r, int c) {
//为空返回
if (nums.length==0)
return nums;
//不能塑造的情况
if(r*c!=nums.length*nums[0].length)
return nums;

int[][] revnums = new int[r][c];
int row = 0,col = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[0].length; j++) {
revnums[row][col] = nums[i][j];
col++;
if (col==c) {
col = 0;
row++;
}
}
}
return revnums;

}


我看了一下其他人的答案:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: