LeetCode Solutions
867. Transpose Matrix
Time: $O(n^2)$ Space: $O(n^2)$
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& A) {
vector<vector<int>> ans(A[0].size(), vector<int>(A.size()));
for (int i = 0; i < A.size(); ++i)
for (int j = 0; j < A[0].size(); ++j)
ans[j][i] = A[i][j];
return ans;
}
};
class Solution {
public int[][] transpose(int[][] A) {
int[][] ans = new int[A[0].length][A.length];
for (int i = 0; i < A.length; ++i)
for (int j = 0; j < A[0].length; ++j)
ans[j][i] = A[i][j];
return ans;
}
}
class Solution:
def transpose(self, A: List[List[int]]) -> List[List[int]]:
ans = [[0] * len(A) for _ in range(len(A[0]))]
for i in range(len(A)):
for j in range(len(A[0])):
ans[j][i] = A[i][j]
return ans