InMATLAB, there is a very useful function called 'reshape', which can reshape amatrix into a new one with different size but keep its original data.
You'regiven a matrix represented by a two-dimensional array, and two positive integers r and c representingthe row number andcolumn number of the wanted reshaped matrix, respectively.
Thereshaped matrix need to be filled with all the elements of the original matrixin the same row-traversing order as they were.
Ifthe 'reshape' operation with given parameters is possible and legal, output thenew reshaped matrix; Otherwise, output the original matrix.
Example1:
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.
Example2:
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 theoriginal matrix.
Note:
1. The height and width of the givenmatrix is in range [1, 100].
2. The given r and c are all positive.
这是一道简单水题,让你将一个矩阵中的所有数字转移到一个r行c列的矩阵中去,r和c是题目给的
直接遍历一遍原来的矩阵就好了,然后把每一个数字取出来,放入目标矩阵中就完成了,这里需要注意的就是在for循环内部不要使用复杂的算术运算,比如对大数使用index/row,或者是index%row,这样会导致程序运行时间的延长
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int x, y;
x = nums.size();
y = nums[0].size();
if (r <= 0 || c <= 0) return nums;
if (x*y != r*c) return nums;
vector<vector<int>> result(r, vector<int>(c, 0));
int indexR = 0,indexC=0;
for(int i=0;i<x;i++)
for (int j = 0; j < y; j++)
{
result[indexR][indexC] = nums[i][j];
if (indexC == c - 1)
{
indexR++;
indexC = 0;
}
else {
indexC++;
}
}
return result;
}
};