LeetCode - Algorithms - 867. Transpose Matrix

Problem

867. Transpose Matrix

Given a matrix A, return the transpose of A.

\( \begin{bmatrix}
1 &2 &3 \\
4 &5 &6 \\
7 &8 &9
\end{bmatrix} \Rightarrow \begin{bmatrix}
1 &4 &7 \\
2 &5 &8 \\
3 &6 &9
\end{bmatrix} \)

Java

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

Submission Detail

  • 36 / 36 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Transpose Matrix.
  • Memory Usage: 40.6 MB, less than 91.67% of Java online submissions for Transpose Matrix.