原题地址(简单)

方法1—二维数组的一维表示

思路

就是找数学上的对应关系,直接看官方题解就可以了,很简单的。

方法2—按行遍历

思路

挨个遍历,更简单》。。。。

代码

  1. class Solution {
  2. public:
  3. vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
  4. vector<vector<int>> vv(r, vector<int>(c));
  5. int row = nums.size(), col = nums[0].size(), i = 0, j = 0;
  6. if(row * col != r * c) return nums;
  7. for(int x = 0; x < r; x++) {
  8. for(int y = 0; y < c; y++) {
  9. vv[x][y] = nums[i][j++];
  10. if(j >= col) {
  11. i++;
  12. j = 0;
  13. }
  14. }
  15. }
  16. return vv;
  17. }
  18. };

时空复杂度

时间566. 重塑矩阵 - 图1 空间566. 重塑矩阵 - 图2 返回数组空间不计算在内