867. Transpose Matrix
阿新 • • 發佈:2018-08-01
cto 大小 輸出矩陣 return urn 分配 over nal spa
題目描述:
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
解題思路:
暴力遍歷原來矩陣的每個元素,放到輸出矩陣的對應位置。
由於veector的內存分配機制,由於已知輸出矩陣的大小,所以在每個vector定義時指定空間大小會節省運行時間。
代碼:
1 class Solution { 2 public: 3 vector<vector<int>> transpose(vector<vector<int>>& A) { 4 vector<vector<int> > res; 5 res.reserve(A[0].size()); 6 for (int i = 0; i < A[0].size(); ++i) { 7 vector<int> tmp; 8 tmp.reserve(A.size()); 9 for (int j = 0; j < A.size(); ++j) { 10 tmp.push_back(A[j][i]); 11 } 12 res.push_back(tmp);13 } 14 return res; 15 } 16 };
867. Transpose Matrix