[LeetCode] 867. Transpose Matrix

Description

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. 1 <= A.length <= 1000
  2. 1 <= A[0].length <= 1000

Analyse

矩阵转置,行列下标互换就行了,简单题

不过原来的二维vector在行列数不相同的情况下会出现空间不够的情况,所以用个新的二维vector存数据

算法复杂度(O(n^2))

vector<vector<int>> transpose(vector<vector<int>>& A)
{
    vector<vector<int>> result;

    int row = A.size();
    int col = A.at(0).size();

    cout << "Row: " << row << endl;
    cout << "Column: " << col << endl;

    for (int i = 0; i < col; i++)
    {
        vector<int> tmp;
        for(int j = 0; j < row; j++)
        {
            tmp.push_back(A.at(j).at(i));
        }
        result.push_back(tmp);
    }

    return result;
}
原文地址:https://www.cnblogs.com/arcsinw/p/9481262.html