Article Directory
topic
867. Transpose matrix
gives you a two-dimensional integer array matrix, and returns the transposed matrix of matrix.
The transposition of a matrix refers to flipping the main diagonal of the matrix and exchanging the row index and column index of the matrix.
Example 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[1,4,7],[2,5,8],[3,6,9]]
Example 2:
输入:matrix = [[1,2,3],[4,5,6]]
输出:[[1,4],[2,5],[3,6]]
prompt:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
-109 <= matrix[i][j] <= 109
Solution (Java)
Index transformation of transposed matrix: (i,j) ->(j,i)
class Solution
{
public int[][] transpose(int[][] matrix)
{
int[][] result = new int[matrix[0].length][matrix.length];
//利用索引变换公式(i,j)->(j,i)
for(int index = 0;index < matrix.length;index++)
{
for(int scan = 0;scan < matrix[index].length;scan++)
{
result[scan][index] = matrix[index][scan];
}
}
return result;
}
}