这题思路我也想到了,基本和题解一样,就是有一句二维vector的初始化不会写,找了一下写法
vector<vector<int>>ans(r,vector<int>(c));
核心代码是这句
ans[i / c][i % c] = mat[i / n][i % n];
完整代码如下
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
int m = mat.size();
int n = mat[0].size();
if (m * n != r * c)return mat;
vector<vector<int>>ans(r,vector<int>(c));
for (int i = 0; i < m * n; i++) {
ans[i / c][i % c] = mat[i / n][i % n];
}
return ans;
}
};
int main() {
Solution test;
vector<vector<int>>mat = { {1,2,3,4} };
int r = 2;
int c = 2;
vector<vector<int>>ans=test.matrixReshape(mat, r, c);
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++) {
cout << ans[i][j];
}
}
}
|