-
SLPHJava:
public class Solution { public int[][] matrixReshape(int[][] nums, int r, int c) { int original_r = nums.length; int original_c = nums[0].length; if (original_r * original_c == r * c) { int[][] result = new int[r][c]; for (int i = 0; i < r * c; i++) { result[i / c][i % c] = nums[i / original_c][i % original_c]; } return result; } else { return nums; } } }
-
SLPHC++解法一:
class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int m = nums.size(), n = nums[0].size(); if (m * n != r * c) return nums; vector<vector<int>> res(r, vector<int>(c)); for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { int k = i * c + j; res[i][j] = nums[k / n][k % n]; } } return res; } };
-
SLPHC++解法二:
class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int m = nums.size(), n = nums[0].size(); if (m * n != r * c) return nums; vector<vector<int>> res(r, vector<int>(c)); for (int i = 0; i < r * c; ++i) { res[i / c][i % c] = nums[i / n][i % n]; } return res; } };
-