Matrix Transposition
easySave
ArrayMatrix
Given a 2D array or matrix of integers, write a function to transpose the matrix. The transpose of a matrix is achieved by flipping the matrix over its diagonal, switching the row and column indices of the matrix.
Example 1
Input
[ [ 1, 2, 3 ], [ 4, 5, 6 ] ]
Output
result: [[1, 4], [2, 5], [3, 6]]
Explanation. The matrix rows and columns are swapped.
Example 2
Input
[ [ 1 ] ]
Output
result: [[1]]
Explanation. A single-element matrix remains the same when transposed.
Example 3
Input
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
Output
result: [[1, 3, 5], [2, 4, 6]]
Explanation. Each element ij of the input matrix becomes element ji in the transposed matrix.
Follow-up: Can you improve your solution to achieve in-place transposition for a square matrix?
Constraints:
1. The matrix will not be empty.\n2. You may assume all rows in the matrix have the same number of columns.
- Views
- 3