Given a matrix `A`, return the transpose of `A`.
The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Note:
1 <= A.length <= 1000
1 <= A[0].length <= 1000
這道題讓我們轉置一個矩陣,在大學的線性代數中,轉置操作應該說是非常的常見。所謂矩陣的轉置,就是把 mxn 的矩陣變為 nxm 的,並且原本在 A[i][j] 位置的數字變到 A[j][i] 上即可,非常的簡單直接。而且由於此題又限定了矩陣的大小范圍為 [1, 1000],所以不存在空矩陣的情況,因而不用開始時對矩陣進行判空處理,直接去獲取矩陣的寬和高即可。又因為之前說了轉置會翻轉原矩陣的寬和高,所以我們新建一個 nxm 的矩陣,然后遍歷原矩陣中的每個數,將他們賦值到新矩陣中對應的位置上即可,參見代碼如下:
class Solution {
public:
vector<vector<int>> transpose(vector<vector<int>>& A) {
int m = A.size(), n = A[0].size();
vector<vector<int>> res(n, vector<int>(m));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
res[j][i] = A[i][j];
}
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/867
參考資料:
https://leetcode.com/problems/transpose-matrix/
https://leetcode.com/problems/transpose-matrix/discuss/146797/C%2B%2BJavaPython-Easy-Understood
[LeetCode All in One 題目講解匯總(持續更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)