一、问题描述
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.
二、思路和程序
思路:首先需要判断能否构造出给定的行列数,即构造后的矩阵中的元素个数要和给定的nums中的元素个数一致。判断完之后,按行遍历nums,将其元素存放到vectormarix中,并记下marix中的元素个数n,当n % c == 0,即n是要构造矩阵的列数的倍数时,将marix存放到 vector<vector>number中,最后生成的 number就是重塑后的矩阵。
程序(C++代码):
vector<vector> matrixReshape(vector<vector>& nums, int r, int c)
{
vector<vector>number;
vectormarix;
int row = nums.size();
int col = nums[0].size();
int n = 0;
if (rc != rowcol)
return nums;
for (int i = 0; i < nums.size(); i++)
{
for (int j = 0; j < nums[i].size(); j++)
{
marix.push_back(nums[i][j]);
n++;
if (n % c == 0)
{
number.push_back(marix);
marix.clear();
}
}
}
return number;
}
三、运行效果
从图中可以看出,代码效果还是不错的。