https://leetcode.com/problems/transpose-matrix/
Given a matrix
A
, return the transpose of A
.
The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]]
public int[][] transpose(int[][] A) {
int R = A.length, C = A[0].length;
int[][] ans = new int[C][R];
for (int r = 0; r < R; ++r)
for (int c = 0; c < C; ++c) {
ans[c][r] = A[r][c];
}
return ans;
}
zip
in Python 3 returns a generator.
Solution that works for both Python 2 and Python 3:
return list(zip(*A))
X.
https://leetcode.com/problems/transpose-matrix/discuss/176903/Java-solution-with-additional-checks-to-use-in-place-wherever-we-can
https://leetcode.com/problems/transpose-matrix/discuss/176903/Java-solution-with-additional-checks-to-use-in-place-wherever-we-can
public int[][] transpose(int[][] A) {
if (A.length == A[0].length) {
inPlace(A);
return A;
}
int[][] B = new int[A[0].length][A.length];
for (int i=0; i<A.length ; i++) {
for (int j=0; j<A[0].length ; j++) {
B[j][i] = A[i][j];
}
}
return B;
}
private void inPlace(int[][] A) {
int col = 0;
for (int i = 0; i<A.length ; i++) {
for (int j=col ; j<A[0].length ; j++) {
int temp = A[i][j];
A[i][j] = A[j][i];
A[j][i] = temp;
}
col++;
}
}
https://leetcode.com/problems/transpose-matrix/discuss/185864/Java-Solution.
- Ideally, we would want to do in-place swapping for this problem. This is only possible when the matrix is a square matrix (NxN). If it is not a square matrix, then we would have to create a new MxN matrix where the original matrix is NxM. Below code is hybrid. If input is square matrix then it does in-place swapping. If not, it makes new matrix element. Time: O(NM), Space: O(NM) or O(1), depends on the input..
public int[][] transpose(int[][] A) {
//if we have a non square matrix, we cannot simply do in-place swapping because it will be index out of bound
//so we have to make a new MxN matrix if the input matrix is NxM where N != M
int numRows = A.length;
int numCols = A[0].length;
if(numRows != numCols){
int[][] transMatrix = new int[numCols][numRows];
int i = 0;
for(int[] row : A){
for(int j=0;j<numCols;j++){
transMatrix[j][i] = row[j];
}
i++;
}
return transMatrix;
// if it is a square matrix, we can simply do in-place flipping to save space..
} else {
for(int i=0;i<numRows;i++){
for(int j=1+i;j<numCols;j++){
int temp = A[i][j];
A[i][j] = A[j][i];
A[j][i] = temp;
}
}
return A;
}
}