Description:
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
思路:本题要求数组的转置。问题不大,主要注意 C++ 中二维数组的初始化操作
vector<vector<int>> ret(column, vector<int>(row,0));
C++ 代码
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& A) {
int column = A[0].size(), row = A.size();
vector<vector<int>> ret(column, vector<int>(row,0));
for (int i = 0; i < row; i++){
for (int j = 0; j < column; j++){
ret[j][i] = A[i][j];
}
}
return ret;
}
};
运行时间:28ms
运行内存:11.4M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于