Question:

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:
  2. nums =
  3. [[1,2],
  4. [3,4]]
  5. r = 1, c = 4
  6. Output:
  7. [[1,2,3,4]]
  8. Explanation:
  9. The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix,
  10. fill it row by row by using the previous list.
  1. Input:
  2. Input:
  3. nums =
  4. [[1,2],
  5. [3,4]]
  6. r = 2, c = 4
  7. Output:
  8. [[1,2],
  9. [3,4]]
  10. Explanation:
  11. There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix.
  12. So output the original matrix.

Solution:

  1. /**
  2. * @param {number[][]} nums
  3. * @param {number} r
  4. * @param {number} c
  5. * @return {number[][]}
  6. */
  7. var matrixReshape = function(nums, r, c) {
  8. if(r*c > nums.length * nums[0].length)return nums;
  9. var res = [];
  10. for(var i = 0 , k = 0 , m = -1 ; i<nums.length ; i ++){
  11. for (var j = 0 ; j < nums[i].length ; j ++ ){
  12. //如果列数k余c为0 ,则开始第二列的遍历
  13. if(k%c === 0){
  14. res.push([])
  15. m++
  16. }
  17. res[m].push(nums[i][j]);
  18. k++;
  19. }
  20. }
  21. return res;
  22. };