1. 程式人生 > >【python3】leetcode 867. Transpose Matrix (easy)

【python3】leetcode 867. Transpose Matrix (easy)

867. Transpose Matrix 

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

轉置矩陣

1 my solution (叉腰自豪臉,fast

矩陣從Amxn ->B nxm、

B的行數是A的列數,所以遍歷A的列進行append

B的第i行是A的第i列,使用listcomp生成一個A的第i列的列表

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

Runtime: 60 ms, faster than 98.75% of Python3