博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
867. Transpose Matrix
阅读量:6967 次
发布时间:2019-06-27

本文共 1020 字,大约阅读时间需要 3 分钟。

题目描述:

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
> transpose(vector
>& A) { 4 vector
> res; 5 res.reserve(A[0].size()); 6 for (int i = 0; i < A[0].size(); ++i) { 7 vector
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 };

 

 

转载于:https://www.cnblogs.com/gsz-/p/9403349.html

你可能感兴趣的文章
Nginx配置文件nginx.conf中文详解
查看>>
无锁队列的实现
查看>>
SpringSecurity重写LogoutFilter
查看>>
使用idfc-proguard-maven-plugin混淆优化Jave Web工程二
查看>>
tomcat 设置内存
查看>>
怎么一边敲代码还能一边赚点钱,一字一字敲的,不喜勿喷哈,IOS手机看进来...
查看>>
libevent evhttp_uri_get_query coredump
查看>>
程序员该当命归何处?
查看>>
Log4j调试
查看>>
Most common latch classes and what they mean
查看>>
java 获取数据库表结构通用方法
查看>>
tc命令——Linux基于IP进行流量限速
查看>>
linux centos yum安装LAMP环境
查看>>
Spring中的@Scope注解
查看>>
我用的Android Studio插件
查看>>
html_3基础
查看>>
在 PHP 中实现整数溢出
查看>>
数据类型和Json格式
查看>>
CodeIgniter连接数据库
查看>>
vi vim配置
查看>>