Given a matrix A
, return the transpose of A
.html
The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.git
Example 1:github
Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:code
Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]]
Note:htm
1 <= A.length <= 1000
1 <= A[0].length <= 1000
這道題讓咱們轉置一個矩陣,在大學的線性代數中,轉置操做應該說是很是的常見。所謂矩陣的轉置,就是把 mxn 的矩陣變爲 nxm 的,而且本來在 A[i][j] 位置的數字變到 A[j][i] 上便可,很是的簡單直接。並且因爲此題又限定了矩陣的大小範圍爲 [1, 1000],因此不存在空矩陣的狀況,於是不用開始時對矩陣進行判空處理,直接去獲取矩陣的寬和高便可。又由於以前說了轉置會翻轉原矩陣的寬和高,因此咱們新建一個 nxm 的矩陣,而後遍歷原矩陣中的每一個數,將他們賦值到新矩陣中對應的位置上便可,參見代碼以下:blog
class Solution { public: vector<vector<int>> transpose(vector<vector<int>>& A) { int m = A.size(), n = A[0].size(); vector<vector<int>> res(n, vector<int>(m)); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { res[j][i] = A[i][j]; } } return res; } };
Github 同步地址:ip
https://github.com/grandyang/leetcode/issues/867leetcode
參考資料:get
https://leetcode.com/problems/transpose-matrix/同步
https://leetcode.com/problems/transpose-matrix/discuss/146797/C%2B%2BJavaPython-Easy-Understood