867. Transpose Matrix
Problem
Return the transpose of matrix: flip it over its main diagonal, turning rows into columns.
Example: [[1,2,3],[4,5,6]] → [[1,4],[2,5],[3,6]]
Element (i, j) moves to (j, i), so an R × C matrix becomes C × R (a new matrix unless it's square).
Complexity: O(R·C).
class Solution:
def transpose(self, matrix: List[List[int]]) -> List[List[int]]:
return [list(col) for col in zip(*matrix)]
assert Solution().transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) == [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
assert Solution().transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]]
assert Solution().transpose([[7]]) == [[7]]
class Solution {
public int[][] transpose(int[][] matrix) {
int R = matrix.length, C = matrix[0].length;
int[][] t = new int[C][R];
for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) t[j][i] = matrix[i][j];
return t;
}
}
func transpose(matrix [][]int) [][]int {
R, C := len(matrix), len(matrix[0])
t := make([][]int, C)
for c := range t {
t[c] = make([]int, R)
for r := 0; r < R; r++ {
t[c][r] = matrix[r][c]
}
}
return t
}