Leetcode 867. Transpose Matrix
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.
For example, the transpose of a matrix:
[
[1,2,3],
[4,5,6],
[7,8,9]
]
is
[
[1,4,7],
[2,5,8],
[3,6,9]
]
Create a New Matrix: Initialize a new matrix transpose
with the dimensions swapped — if the original matrix is m x n
, the new matrix will be n x m
.
Iterate and Assign Values: Iterate over the original matrix, and for each element at position (i,j)
, place it in the new matrix at position (j,i)
.
Return Result: Return the newly created transposed matrix.
public class Solution {
public int[][] transpose(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int[][] transpose = new int[n][m];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
transpose[j][i] = matrix[i][j];
}
}
return transpose;
}
}
m x n
matrix once, making a single operation for each. Thus, the complexity is proportional to the number of elements in the matrix.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?