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:
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.
Input:
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.
Solution:
/**
* @param {number[][]} nums
* @param {number} r
* @param {number} c
* @return {number[][]}
*/
var matrixReshape = function(nums, r, c) {
if(r*c > nums.length * nums[0].length)return nums;
var res = [];
for(var i = 0 , k = 0 , m = -1 ; i<nums.length ; i ++){
for (var j = 0 ; j < nums[i].length ; j ++ ){
//如果列数k余c为0 ,则开始第二列的遍历
if(k%c === 0){
res.push([])
m++
}
res[m].push(nums[i][j]);
k++;
}
}
return res;
};