解答:
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int m = nums.size();
int n = nums[0].size();
if (m * n != r * c) {
return nums;
}
vector<vector<int>> ans(r, vector<int>(c));
for (int x = 0; x < m * n; ++x) {
ans[x / c][x % c] = nums[x / n][x % n];
}
return ans;
}
};
1.vector建立二维数组:
vector<vector<int>> arr(ROW, vector<int>(COLUMN));
2.二维数组的遍历:
除了双重for循环以外,可以用整除及余数来控制行和列。
for (int x = 0; x < m * n; ++x)
{
ans[x / c][x % c] = nums[x / n][x % n];
}