867. Transpose Matrix

867. Transpose Matrix

Question

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.

Solution

记录一个新数组res[][]。

双重循环,交换下标将matrix[i][j]复制到res[j][i],最后返回。

Code

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int[][] transpose(int[][] matrix) {
int[][] res = new int[matrix[0].length][matrix.length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
res[j][i] = matrix[i][j];
}
}
return res;
}
}
Author

Xander

Posted on

2022-06-02

Updated on

2022-06-01

Licensed under

Comments