transpose-matrix
when I realized I f*k up my own website…
ok on to the topic..
868. [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]]
Note:
1 <= A.length <= 1000
1 <= A[0].length <= 1000
var transpose = function(A) {
if (A.length ===0 || A[0].length === 0) return A;let res = new Array(A[0].length);for (let i = 0; i < res.length; i ++) {res[i] = new Array(A.length);for (let j = 0; j < res[i].length; j ++) {res[i][j] = A[j][i];}}return res;}
### Analysis:
This is question is pretty straightforward. Since its asking about the transpose of a matrix, it’s essentially asking you to replace matrix[i][j] with matrix[j][i]. But where is the gotcha here?
Well at first, I did a double loop for the row and col, and used a swap mechanism to swap the matrix[i][j] with matrix[j][i].. pretty obvious right? guess what, the matrix stayed the same!!
in Javascript, is there a way to do in-place transpose without needing an extra space?
```
var transpose = function(A) {
return A[0].map((val, ind) => A.map(row => row[ind]));
};
```
**This, essentially, is to iterate the array vertically, instead of of horizontally, and return the result of that, which implicitly assigns the new array to another variable…**
So well , let me think about it later..