link
https://leetcode-cn.com/problems/transpose-matrix/
time consuming
Problem solving: 4 min
Problem solving: 4 min
Title
Gives you a two-dimensional integer array matrix, and returns the transposed matrix of the matrix.
The transposition of a matrix refers to flipping the main diagonal of the matrix and exchanging the row index and column index of the matrix.
prompt:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 1000
- 1 <= m * n <= 10^5
- -10^9 <= matrix[i][j] <= 10^9
Ideas
According to the definition of the transpose matrix-exchange row and column index, see the code for details.
Time complexity: O (m ∗ n) O(m*n)O ( m∗n)
AC code
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<vector<int>> ans(n, vector<int>(m));
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
ans[j][i] = matrix[i][j];
}
}
return ans;
}
};