您的位置:首页 > 其它

Leetcode 566. Reshape the Matrix(Easy)

2018-03-09 11:27 417 查看

1.题目

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.翻译:在MATLAB中,有一个很有用的功能叫“矩阵变维”,它可以把一个矩阵转成一个新矩阵,新矩阵有不同的尺寸但是保持原有尺寸。给你一个二维数组,两个正整数r和c,代表希望变成了矩阵的行数和列数。如果矩阵变维操作给定的参数是可以的并合法的,输出新的变维数组。否则,输出原有的矩阵。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.

2.思路

一种比较笨的方法,原矩阵行、列数分别为x.y,如果x*y==r*c,则表示可以进行转换,否则输出原数组。
如果可以转换,申请一个长为x*y的一维数组,先把原矩阵中所有数记起来,再拼接到新矩阵中。

3.算法

public int[][] matrixReshape(int[][] nums, int r, int c) {
if(nums==null)return null;
int x=nums.length;
int y=nums[0].length;
if(x*y!=r*c)return nums;

int[] temp=new int[x*y];
int[][] res=new int[r][c];
int i=0;

for(int j=0;j<x;j++){
for(int k=0;k<y;k++){
temp[i++]=nums[j][k];
}
}

i=0;
for(int j=0;j<r;j++){
for(int k=0;k<c;k++){
res[j][k]=temp[i++];
}
}

return res;
}

4.总结

遇到的一个问题就是,忘记申请新的二维数组了,居然试图直接改变nums.别的还比较简单,但是算法时间复杂度略高。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: