matrix
867. Transpose Matrix
tip
- Given a 2D integer array matrix, return the transpose of matrix.
- The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices.
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[1,4,7],[2,5,8],[3,6,9]]
示例 2:
输入:matrix = [[1,2,3],[4,5,6]]
输出:[[1,4],[2,5],[3,6]]
class Solution {
public int[][] transpose(int[][] matrix) {
int rows = matrix.length; // 行数
int cols = matrix[0].length; // 列数
// 所谓转置举证,就是行变列,列边行
int[][] result = new int[cols][rows];
// 行列的值互换
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
}