867. 转置矩阵
题目:给你一个二维整数数组 matrix, 返回 matrix 的 转置矩阵 。矩阵的 转置 是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[1,4,7],[2,5,8],[3,6,9]]
示例 2:
输入:matrix = [[1,2,3],[4,5,6]]
输出:[[1,4],[2,5],[3,6]]
1.原创
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int n = matrix.size();
int m = matrix[0].size();
vector<vector<int> > res(m, vector<int>(n));//定义指定大小的二维vector
for (int i=0;i<n;++i){
for (int j=0;j<m;++j){
res[j][i] = matrix[i][j];
}
}
return res;
}
};
2.题解
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
vector<vector<int> >ans;
for(int i=0; i<matrix[0].size(); i++){
ans.push_back({});
for(int j=0; j<matrix.size(); j++){
ans[i].push_back(matrix[j][i]);
}
}
return ans;
}
};
作者:wu-tang-ka-bu-qi-nuo
链接:https://leetcode-cn.com/problems/transpose-matrix/solution/867-zhuan-zhi-ju-zhen-er-wei-vector-by-w-ocxe/