LeetCode-Java-867. Transpose Matrix

题目

Given a matrix A, return the transpose of A.
给定一个矩阵A,返回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]]

代码

class Solution {
    public int[][] transpose(int[][] A) {
        if(A==null)
        {
            return  null;
        }
        int lena = A.length;
        int lenb = A[0].length;
        int[][] B = new int[lenb][];
        for(int i=0;i<lenb;i++)
        {
            B[i] = new int[lena];
        }
        for(int i=0;i<lena;i++)
        {
            int len = A[i].length;
            for(int j = 0;j<len;j++)
            {
                B[j][i] = A[i][j];
            }
        }
        return B;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38345606/article/details/81040973