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

被折叠的 条评论
为什么被折叠?



