566. Reshape the Matrix

本文介绍了一种将矩阵按指定行数和列数重塑的算法,并提供了一个简洁高效的实现方案。该算法能够判断输入的有效性并优雅地处理无法重塑的情况。

问题描述:将一个矩阵按照输入的行列数重新排列,如果不能按照输入的行列数重新排列,返回原矩阵。
思路:没什么好想的,一边遍历一边计算对应位置。
原答案:

    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int col=nums.length;
        int row=0;
        if(col==0)
            return nums;
        else{
            row=nums[0].length;
            if(row==0)
                return nums;
            else{
                if(col*row!=r*c)
                    return nums;
                else{
                    int[][] res=new int[r][c];
                    for(int i=0;i<r;i++){
                        for(int j=0;j<c;j++){
                            int count=i*c+j+1;
                            if(count%row==0){
                                res[i][j]=nums[count/row-1][row-1];
                            }else{
                                int newCol=count/row;
                                res[i][j]=nums[newCol][count-(row*(newCol))-1];
                            }
                        }
                    }
                return res;
                }
            }
        }
    }

最佳答案:

    public int[][] matrixReshape(int[][] nums, int r, int c) {
        int[][] res = new int[r][c];
        if (nums.length == 0 || r * c != nums.length * nums[0].length)
            return nums;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums[0].length; j++) {
                res[count / c][count % c] = nums[i][j];
                count++;
            }
        }
        return res;
    }

比起自己的代码简洁了不是一星半点。写代码时候总喜欢搞些自作聪明的弯弯道道。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值