566. 重塑矩阵【ans[x / c][x % c] = nums[x / n][x % n]】

566. 重塑矩阵

在这里插入图片描述


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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值