Transpose Matrix
Problem
Given a 2D integer array matrix
, return the transpose of matrix
.
The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix’s row and column indices.
Constraints
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
-109 <= matrix[i][j] <= 109
Solution
The problem Transpose Matrix
can be solved by simply switching the matrix’s row and column indices.
Implementation
static const int fast_io = []()
{
std::ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution
{
public:
vector<vector<int>> transpose(vector<vector<int>> &matrix)
{
vector<vector<int>> ret(matrix[0].size(), vector<int>(matrix.size(), 0));
for (int i = 0; i < matrix.size(); i++)
for (int j = 0; j < matrix[i].size(); j++)
ret[j][i] = matrix[i][j];
return ret;
}
};