C代码1:
int** matrixReshape(int** nums, int numsSize, int* numsColSize, int r, int c, int* returnSize, int** returnColumnSizes) {
int m = numsSize; // 将数组作为指针传递过来,这个是复制还是引用?--引用
int n = numsColSize[0];
if (m * n != r * c) {
*returnSize = numsSize; // 行
*returnColumnSizes = numsColSize;
return nums;
}
*returnSize = r; // 行
*returnColumnSizes = malloc(sizeof(int) * r); // 创建数组行(数组存值)
int** ans = malloc(sizeof(int*) * r); // 返回体,创建数组行(存指针) 二者第一步都是创建数组,区别存放值/地址
for (int i = 0; i < r; i++) {
(*returnColumnSizes)[i] = c; // 数组存列值
ans[i] = malloc(sizeof(int) * c); // 数组存数组(指针)
}
for (int x = 0; x < m * n; ++x) {
ans[x / c][x % c] = nums[x / n][x % n];
}
return ans;
}
Java代码1:
public int[][] matrixReshape(int[][] nums, int r, int c) {
int m = nums.length;
int n = nums[0].length;
if (m * n != r * c) {
return nums;
}
int[][] ans = new int[r][c];
for (int x = 0; x < m * n; ++x) { // 没法做两个for循环
ans[x / c][x % c] = nums[x / n][x % n]; // 对列整除、求余
}
return ans;
}