题目描述:
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> transpose(vector >& A) { 4 vector > res; 5 res.reserve(A[0].size()); 6 for (int i = 0; i < A[0].size(); ++i) { 7 vector 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 };