2023-12-10 Daily Challenge
Today I have done leetcode's December LeetCoding Challenge with cpp
.
December LeetCoding Challenge 10
Description
Transpose Matrix
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.
Example 1:
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: matrix = [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]]
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
-109 <= matrix[i][j] <= 109
Solution
auto speedup = [](){
cin.tie(nullptr);
cout.tie(nullptr);
ios::sync_with_stdio(false);
return 0;
}();
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& matrix) {
int rows = matrix.size();
int cols = matrix.front().size();
vector<vector<int>> answer;
for(int i = 0; i < cols; ++i) {
vector<int> row(rows);
for(int j = 0; j < rows; ++j) {
row[j] = matrix[j][i];
}
answer.emplace_back(row);
}
return move(answer);
}
};
// Accepted
// 36/36 cases passed (7 ms)
// Your runtime beats 97.84 % of cpp submissions
// Your memory usage beats 13.79 % of cpp submissions (10.8 MB)