在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据。
给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。
如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300

class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
if(mat.size()*mat[0].size()!=r*c) return mat;
vector<int> temp;
vector<vector<int>> res;
int h=0,l=0;
for( int i = 0 ; i < mat.size();i++)
{
for( int j =0 ; j < mat[0].size();j++)
{
if(l<c)
{
temp.push_back(mat[i][j]);
l++;
}
else
{
res.push_back(temp);
temp.clear();
l=0;
temp.push_back(mat[i][j]);
l++;
}
}
}
res.push_back(temp);
return res;
}
};
思路:先判断能否成功转换,不能直接返回原矩阵,如果能的话逐行遍历矩阵存储在vector<int>temp中,然后当temp.size为c时temp存储到res中,并清空temp重新开始。
文章讲解了如何在MATLAB中使用reshape函数进行矩阵重塑,遵循行优先顺序,提供代码实现。
478

被折叠的 条评论
为什么被折叠?



