【leetcode】867.Transpose Matrix解题报告

将一个矩阵转置

方法一:新建一个转置后的矩阵的shape,比如3*2 的矩阵对应的2*3的矩阵,然后依次遍历原矩阵,把遍历到的元素放到新矩阵对应的位置

python

class Solution:
    def transpose(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        width = len(A[0])
        heigth = len(A)
        res = [[0 for i in range(heigth)] for j  in range(width)]
        for i in range(heigth):
            for j in range(width):
                res[j][i] = A[i][j]
        return res

该方法beat28.66%

方法二:用python的列表推导式

class Solution:
    def transpose(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        return [[row[i] for row in A] for i in range(len(A[0]))]

该方法beat6.4% emmm…..

方法三:用python自带的zip函数,解压完转换成list即可

class Solution:
    def transpose(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        return list(zip(*A))

该方法beat99.4%

方法四:常规操作
python

class Solution:
    def transpose(self, A):
        """
        :type A: List[List[int]]
        :rtype: List[List[int]]
        """
        res = []
        for i in range(len(A[0])):
            res.append([line[i] for line in A])
        return res

这也beat 99.4%

Java

class Solution {
    public int[][] transpose(int[][] A) {
        int height = A.length;
        int width  = A[0].length;
        int[][] res = new int[width][height];
        for(int i=0;i<height;i++)
            for(int j=0;j<width;j++){
            res[j][i] =A[i][j];
            }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/dpengwang/article/details/81295634