题目地址:
https://leetcode.com/problems/reshape-the-matrix/
给定一个矩阵,要求将其变换为一个行列的矩阵,使得两者按行遍历结果一样。若无法变换,则返回原矩阵。用一维转二维的方法,将一个一维座标和二维座标做一一对应即可。代码如下:
public class Solution {
public int[][] matrixReshape(int[][] nums, int r, int c) {
int n = nums.length, m = nums[0].length;
// 如果方格个数不一样则不可能转换成功,返回原数组即可
if (n * m != r * c) {
return nums;
}
int[][] res = new int[r][c];
int idx = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// idx对应的二维座标是(idx / c, idx % c)
res[idx / c][idx % c] = nums[i][j];
idx++;
}
}
return res;
}
}
时间复杂度,空间(不包含返回结果的空间)。