LeetCode 566. Reshape the Matrix (重塑矩阵)

时间:2022-07-18 13:35:04

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.

题目标签:Array

  这道题目给了我们一个matrix 2d array, 让我们根据给的r 和 c 来重新塑造一个新的矩阵。那么首先我们先判断一下,给的r 和 c 能不能用来塑造一个2d array。比较一下总数就可以了。接下来我们就重塑一个2d array 根据给的r 和c,遍历原来的nums, 设两个int,col 和 row, 对于旧的nums 2d array,当我们每次遍历一行里的每一个数字,我们每次col++,意思就是增加列。一旦当我们自己数的col 列 = c 给的列的时候,我们就更新col 列 = 0, 并且row++。 每一次的数字利用自己计数的row 和 col 代入, res[row][col]。

Java Solution:

Runtime beats 38.21%

完成日期:05/10/2017

关键词:Array

关键点:自己来计数row and column, 并存入每一个int到新的2d array里面

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

参考资料:N/A

LeetCode 算法题目列表 - LeetCode Algorithms Questions List