zoukankan      html  css  js  c++  java
  • leetcode-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

     

    要完成的函数:

    vector<vector<int>> transpose(vector<vector<int>>& A) 

    说明:

    1、给定一个二维vector,命名为A,要求把A转置,输出转置之后的二维vector。

    不过这里的二维vector不一定是方阵(也就是行数和列数不一定相等)。

    比如[[1,2,3],[4,5,6]],转置之后结果是[[1,4],[2,5],[3,6]],其实也就是按列读取的结果。

    2、明白题意,这道题一点也不难。

    代码如下:(附详解)

        vector<vector<int>> transpose(vector<vector<int>>& A) 
        {
            int hang=A.size(),lie=A[0].size();//得到行数和列数
            vector<vector<int>>res;
            vector<int>res1;
            for(int j=0;j<lie;j++)//外层循环是列的循环
            {
                for(int i=0;i<hang;i++)//内层循环是行的循环
                {
                    res1.push_back(A[i][j]);//不断地把每一行同一列的值插入到res1中去
                }
                res.push_back(res1);//res1的结果插入到res中
                res1.clear();//清空res1
            }
            return res;
        }
    

    上述代码十分简洁,就是vector的不断插入比较费时间。我们也可以改成先定义好二维vector的长度,接着更新数值就好,这样就不用频繁地申请内存空间了。

    但对于这道题,花费的时间没有相差太多。

    上述代码实测16ms,beats 98.72% of cpp submissions。

  • 相关阅读:
    Git checkout on a remote branch does not work
    制作ubuntu U盘安装盘
    Angular 2.0 和 1.x比较
    图文浅谈css3
    前后端数据交互方法
    CSS实现响应式全屏背景图
    html5图片高度自适应解决方法
    2014年最后100天,想说点啥。
    js常用代码
    html5+css3开发总结
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9333066.html
Copyright © 2011-2022 走看看