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

这题是给定一个矩阵,然后对着对角线翻转后,求出反转后的矩阵。这题根据题目给的例子很容易推导出规律:新的矩阵的每一行,均为老矩阵对应每一行的第N个元素组成的,N为老矩阵每一行的尺寸。知道这个规律后很容易写出代码:

class Solution {
public:
    vector<vector<int>> transpose(vector<vector<int>>& A) {
        vector<vector<int>> res;
        size_t columns = A[0].size();

        for (size_t i = 0; i < columns; i++) {
            vector<int> nrow;
            nrow.reserve(A.size());

            for (auto &row : A) {
                nrow.push_back(row[i]);
            }
            res.push_back(std::move(nrow));
        }

        return res;
    }
};
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day