1.题目
LeetCode: 566. 重塑矩阵
【easy】
2.解题
方法一:直接法
获取nums的长h和宽w,如果h * w != r * c,则直接返回nums,否则将原数组元素转移到新数组,即n%w为行的个数,n/w为列的个数。
java:
class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int h = nums.length;
int w = nums[0].length;
if (h * w != r * c) return nums;
int[][] res = new int[r][c];
int n = 0;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
res[i][j] = nums[n / w][n % w];
n++;
}
}
return res;
}
}
时间复杂度:O(rc)
空间复杂度:O(1)