867. Transpose Matrix

被 KO 的題目類型

LeetCode

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]]

怎麼解

Matrix 題目都要先找 pattern 再解,所以這一題原本的 index 是以下

[0, 0], [0, 1], [0, 2]
[1, 0], [1, 1], [1, 2]
[2, 0], [2, 1], [2, 2]

會變以下,然後重要的是找出 pattern

// i 指 第一個 index, j 是第二個 index
[0, 0], [1, 0], [2, 0] // row 0
[0, 1], [1, 1], [2, 1] // row 1
[0, 0], [1, 2], [2, 2] // row 2

觀察 j 就是固定 row 的數字,而 i 都是 0, 1, 2

var transpose = function(lists) {
  // 反轉過後原本 Row 會變 Column,Column 變 Row
  let columns = matrix[0].length;
  let rows = matrix.length;
  let newMatrix = []


  for(let y=0; y< columns; y++){
      let tmp = []
      for(let x=0; x< rows; x++){
          tmp.push(matrix[x][y])
      }
      newMatrix.push(tmp)
   }

    return newMatrix
};

console.log(transpose([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]))

Last updated

Was this helpful?