Leetcode 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]]
提示:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 1000
- 1 <= m * n <= 105
- -109 <= matrix[i][j] <= 10^9
Code:
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
vector<vector<int>>res;
if(matrix.size()==matrix[0].size())
{
for(int i=0;i<matrix.size();i++)
{
vector<int>sub=matrix[i];
for(int j=i;j<sub.size();j++)
{
if(i==j)
continue;
else
{
swap(matrix[i][j],matrix[j][i]);
}
}
}
return matrix;
}
else
{
for(int i=0;i<matrix[0].size();i++)
{
vector<int>sub;
for(int j=0;j<matrix.size();j++)
{
sub.push_back(matrix[j][i]);
}
res.push_back(sub);
}
return res;
}
return res;
}
};
标签:matrix,示例,转置,矩阵,867,int,vector,Leetcode 来源: https://www.cnblogs.com/xiaohai123/p/16299324.html