zoukankan      html  css  js  c++  java
  • 867. Transpose Matrix

    题目描述:

    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

    解题思路:

    暴力遍历原来矩阵的每个元素,放到输出矩阵的对应位置。

    由于veector的内存分配机制,由于已知输出矩阵的大小,所以在每个vector定义时指定空间大小会节省运行时间。

    代码:

     1 class Solution {
     2 public:
     3     vector<vector<int>> transpose(vector<vector<int>>& A) {
     4         vector<vector<int> > res;
     5         res.reserve(A[0].size());
     6         for (int i = 0; i < A[0].size(); ++i) {
     7             vector<int> tmp;
     8             tmp.reserve(A.size());
     9             for (int j = 0; j < A.size(); ++j) {
    10                 tmp.push_back(A[j][i]);
    11             }
    12             res.push_back(tmp);
    13         }
    14         return res;
    15     }
    16 };
  • 相关阅读:
    [CodeForces
    [CodeChef]RIN(最小割)
    [Bzoj3894]文理分科(最小割)
    [Poj3469]Dual Core CPU(最小割)
    MySQL- 锁(3)
    MySQL- 锁(1)
    MySQL- 锁(2)
    MySQL-中文全文检索
    Solr
    多线程编程-之并发编程:同步容器
  • 原文地址:https://www.cnblogs.com/gsz-/p/9403349.html
Copyright © 2011-2022 走看看