1. 程式人生 > >LeetCode 867 Transpose Matrix 解題報告

LeetCode 867 Transpose Matrix 解題報告

ice leet switch 要求 行數 return 相等 flip self

題目要求

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.

題目分析及思路

題目要求得到矩陣的轉置矩陣。可先得到一個行數與原矩陣列數相等、列數與原矩陣行數相等的矩陣,再對原矩陣進行遍歷。

python代碼?

class Solution:

def transpose(self, A: ‘List[List[int]]‘) -> ‘List[List[int]]‘:

rows, cols = len(A), len(A[0])

res = [[0] * rows for _ in range(cols)]

for row in range(rows):

for col in range(cols):

res[col][row] = A[row][col]

return res

LeetCode 867 Transpose Matrix 解題報告