[leetcode] 867. Transfer matrix problem solving Report

Keywords: Python Java

Transpose a matrix

Method 1: create a new shape of the transposed matrix, such as the 2 * 3 matrix corresponding to the 3 * 2 matrix, then traverse the original matrix in turn, and put the traversed elements in the corresponding positions of the new matrix

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

The method beat 28.66%

Method 2: using python's list derivation

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]))]

The method beat 6.4% emmm ..

Method 3: use the zip function of python to decompress and convert it to list

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

The method beat 99.4%

Method 4: routine operation
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

It's also 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;
    }
}

Posted by Pilly on Thu, 23 Jan 2020 07:28:55 -0800