leetcode566:重塑矩阵

在这里插入图片描述

class Solution {
    public int[][] matrixReshape(int[][] nums, int r, int c) {

        // 首先判断reshape操作数是否可行合理,通过两者间的元素个数是否相等判断
        int countPre = nums.length * nums[0].length;  // 原矩阵的元素个数
        int countPost = r * c;  // 重塑矩阵的元素个数

        // 判断合理性
        // 不合理
        if(countPre != countPost) return nums;

        // 合理,开始重塑
        // 初始化一个二维数组
        int[][] resultArr = new int[r][c];
        
        // 定义标志位,判断二维数组中行和列是否填满
        int rowIndex = 0;
        int colIndex = 0;

        // 对原数组进行行遍历,再resultArr中添加元素
        for(int i = 0; i < nums.length; i++){
            for(int j = 0; j < nums[0].length; j++){

                if(colIndex < c){
                    // 一行未满,继续添加
                    resultArr[rowIndex][colIndex] = nums[i][j];
                    // 列标志位 + 1
                    colIndex ++;
                }
                if(colIndex == c){
                    // 一行已满,行标志位 + 1
                    rowIndex++;
                    // 列标志位清零
                    colIndex = 0;
                }
            }
        }
        return resultArr;
    }
}

在这里插入图片描述


第二种方法,参考题解的映射

class Solution {
    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) {
            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、付费专栏及课程。

余额充值