题目描述:
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
要完成的函数:
vector<vector<int>> transpose(vector<vector<int>>& A)
说明:
1、给定一个二维vector,命名为A,要求把A转置,输出转置之后的二维vector。
不过这里的二维vector不一定是方阵(也就是行数和列数不一定相等)。
比如[[1,2,3],[4,5,6]],转置之后结果是[[1,4],[2,5],[3,6]],其实也就是按列读取的结果。
2、明白题意,这道题一点也不难。
代码如下:(附详解)
vector> transpose(vector >& A) { int hang=A.size(),lie=A[0].size();//得到行数和列数 vector >res; vector res1; for(int j=0;j
上述代码十分简洁,就是vector的不断插入比较费时间。我们也可以改成先定义好二维vector的长度,接着更新数值就好,这样就不用频繁地申请内存空间了。
但对于这道题,花费的时间没有相差太多。
上述代码实测16ms,beats 98.72% of cpp submissions。