如果矩阵 matrix 为 m 行 n 列,则转置后的矩阵 matrix}^\text{T 为 n 行 m 列,且对任意 0 \le i<m 和 0 \le j<n,都有 matrix}^\text{T}[j][i]=\textit{matrix}[i][j]。
创建一个 n 行 m 列的新矩阵,根据转置的规则对新矩阵中的每个元素赋值,则新矩阵为转置后的矩阵。
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { publicint[][] transpose(int[][] matrix) { intm= matrix.length, n = matrix[0].length; int[][] transposed = newint[n][m]; for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { transposed[j][i] = matrix[i][j]; } } return transposed; } }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10
var transpose = function(matrix) { const m = matrix.length, n = matrix[0].length; const transposed = newArray(n).fill(0).map(() =>newArray(m).fill(0)); for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { transposed[j][i] = matrix[i][j]; } } return transposed; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functranspose(matrix [][]int) [][]int { n, m := len(matrix), len(matrix[0]) t := make([][]int, m) for i := range t { t[i] = make([]int, n) for j := range t[i] { t[i][j] = -1 } } for i, row := range matrix { for j, v := range row { t[j][i] = v } } return t }
[sol1-Python3]
1 2 3 4 5 6 7 8
classSolution: deftranspose(self, matrix: List[List[int]]) -> List[List[int]]: m, n = len(matrix), len(matrix[0]) transposed = [[0] * m for _ inrange(n)] for i inrange(m): for j inrange(n): transposed[j][i] = matrix[i][j] return transposed
[sol1-Python3_oneline]
1 2 3
classSolution: deftranspose(self, matrix: List[List[int]]) -> List[List[int]]: returnlist(list(row) for row inzip(*matrix))
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: vector<vector<int>> transpose(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); vector<vector<int>> transposed(n, vector<int>(m)); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { transposed[j][i] = matrix[i][j]; } } return transposed; } };
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int** transpose(int** matrix, int matrixSize, int* matrixColSize, int* returnSize, int** returnColumnSizes) { int m = matrixSize, n = matrixColSize[0]; int** transposed = malloc(sizeof(int*) * n); *returnSize = n; *returnColumnSizes = malloc(sizeof(int) * n); for (int i = 0; i < n; i++) { transposed[i] = malloc(sizeof(int) * m); (*returnColumnSizes)[i] = m; } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { transposed[j][i] = matrix[i][j]; } } return transposed; }
复杂度分析
时间复杂度:O(mn),其中 m 和 n 分别是矩阵 matrix 的行数和列数。需要遍历整个矩阵,并对转置后的矩阵进行赋值操作。