leetcode 867. Transpose Matrix(二维数组)

本文介绍了一种求矩阵转置的方法,通过新建一个矩阵并利用B[i][j]=A[j][i]的方式完成矩阵的转置操作。文章给出了具体的实现代码,并列举了两个示例进行说明。

Given a matrix A, return the transpose of A.

The transpose of a matrix is the matrix flipped over it’s main diagonal, switching the row and column indices of the matrix.

Example 1:

Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:

Input: [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]

Note:

1 <= A.length <= 1000
1 <= A[0].length <= 1000

题意:求矩阵的转置,矩阵可能不是方阵

思路:新建一个B矩阵,B[i][j]=A[j][i]

bug:1、在遍历时对每行每列长度总是搞混
2、一开始没想到新建,就在A矩阵上转换值,错误覆盖
3、没有取n,m,总是出现时间超出

知识点:
1、初始化二维数组int[][] B = new int[n][m],n.m常数
2、二维数组的行列长,例如A={{1,2,3},{4,5,6}}
A[i][j],行数=A.length,列数=A[0].length
3、把要计算的length先赋值n,m,后面再使用就不用计算了,节省时间

class Solution {
    public int[][] transpose(int[][] A) {
        int n = A[0].length;
        int m = A.length;//赋值省时
        int[][] B = new int[n][m];//B是A的行列颠倒
        for(int i=0;i<n;i++) {//注意是创建B,要按照B的行列循环,i与n对应,j与m对应
            for(int j=0;j<m;j++) {
                B[i][j] = A[j][i];
            }
        }
        return B;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值