链接
https://leetcode-cn.com/problems/reshape-the-matrix/
耗时
解题:17 min
题解:10 min
题意
在MATLAB中,有一个非常有用的函数 reshape,它可以将一个矩阵重塑为另一个大小不同的新矩阵,但保留其原始数据。
给出一个由二维数组表示的矩阵,以及两个正整数r和c,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的行遍历顺序填充。
如果具有给定参数的reshape操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
思路
按重塑矩阵的位置循环填充,首先算出按行遍历当前元素是总共的第几个,然后重新计算当前元素在原来矩阵的行列下标,将原来矩阵的这个元素填充进重塑矩阵。
时间复杂度: O ( r ∗ c ) O(r*c) O(r∗c)
AC代码
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int ori_r = nums.size();
int ori_c = nums[0].size();
if((ori_r*ori_c != r*c) || (ori_r == r && ori_c == c)) {
return nums;
}
vector<vector<int>> ans(r, vector<int>(c));
for(int i = 0; i < r; ++i) {
for(int j = 0; j < c; ++j) {
int cnt = i*c+j;
int x = cnt/ori_c;
int y = cnt%ori_c;
ans[i][j] = nums[x][y];
}
}
return ans;
}
};