For a source matrix, we would create a
transposed matrix. We copy each row of the source matrix into a column of transposed.
- Destination row index: The length of the source row gives the row indices of the destination column.
- Destination col index: Index of the source row is the index of the destination column.
Time: , space:
.
class Solution:
def copy_row_to_column(self, src_row, transposed, dst_col_index) -> None:
for dst_row_index, x in enumerate(src_row):
transposed[dst_row_index][dst_col_index] = x
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
m, n = len(matrix), len(matrix[0])
# 3 X 2 --> 2 X 3
transposed = [
[0] * m for _ in range(n)
]
for dst_col_index, src_row in enumerate(matrix):
self.copy_row_to_column( src_row, transposed, dst_col_index )
return transposed
Leave a comment