LeetCode-566. Reshape the Matrix
来源:互联网 发布:软件著作权申请费用 编辑:程序博客网 时间:2024/05/21 11:24
Description:
Example 1:
Example 2:
Note:
Solution 1 (C++):
Solution 2 (C++):
算法分析:
Easy难度的题目,算法思路都不简单,主要打好编程基础,然后让自己能快速准确一次性的No Bug通过。简单的说一下这道题的思路:首先要注意读题,题目中说,如果矩阵变形失败,那么就要返回原矩阵,那么有个问题就是,为什么矩阵变形会失败,思考一下,不难得出答案:新矩阵与原矩阵的元素个数不等,直接反映到就是两个矩阵的行列数乘积不等。那么如果可以成功转换,就需要将原矩阵里的元素对应输入到新矩阵中。即可。
程序分析:
这道题的程序我bug了好几次。编程功底需要加强。主要要解决:1.如何获取一个已知二维vector的行和列;2.如何构造一个新的已知行和列的二维vector;3.如何进行两个矩阵之间的数据传输。
1.获取一个已知二维vector的行和列:
//vector<vector<int>>& numsint numsr=nums.size();int numsc=nums[0].size();需要注意一般用size()函数来获取vector的长度。不是用length。length一般用来获取字符串的长度。
2.构造一个新的已知行和列的二维vector:
vector<vector<int>> res(r, vector<int>(c, 0));可以抽象一下:
vector<vector<类型>> 名称(行数,vector<类型>(列数,0));3.进行两个矩阵之间的数据传输:
这里要注意到我两个答案用了两种方法,Solution 1是自己第一遍写的答案,Solution 2是参考了别人的代码然后改进的。从代码简介度上看,后者更简洁漂亮;但好像运算速度上,前者不差。所以,在这里着重介绍后者的编程方法。
int o=numsr*numsc;...for (int i = 0; i < o; i++) { res[i / c][i % c] = nums[i / numsc][i % numsc];}由于两个矩阵元素总数相同。这里用行数c,numsc,来表达各自矩阵的行与列。其中,行表示为:i/c;列表示为:i%c;而i是从0到行*列-1的整数。这种技巧值得学习。
//=====================BY zy2317878=====================//
//===================博观约取,厚积薄发===================////=========================END=========================//
阅读全文
0 0
- leetcode 566. Reshape the Matrix
- LeetCode 566. Reshape the Matrix
- [LeetCode]566. Reshape the Matrix
- [leetcode]566. Reshape the Matrix
- LeetCode:566. Reshape the Matrix
- leetcode 566. Reshape the Matrix
- LeetCode | 566. Reshape the Matrix
- leetcode-566. Reshape the Matrix
- LeetCode 566.Reshape the Matrix
- LeetCode: 566. Reshape the Matrix
- LeetCode-566. Reshape the Matrix
- LeetCode * 566.Reshape the Matrix
- LeetCode: 566. Reshape the Matrix
- leetcode.566.Reshape the Matrix
- LeetCode 566. Reshape the Matrix
- [LeetCode] 566. Reshape the Matrix
- 【LeetCode】566. Reshape the Matrix
- [LeetCode]566. Reshape the Matrix
- csdn博客,帮助我学习更多的网络应用技术,关注5年都没注册过的博客
- 单例模式的七种写法
- 现代软件工程_团队项目_阿尔法阶段_第四次会议记录_2017.11.20
- 【Scikit-Learn 中文文档】五:内核岭回归
- 链表问题---一种怪异的节点删除方式
- LeetCode-566. Reshape the Matrix
- 匠牛社区AM5728 网口使用
- oracle PLSQL配置文件
- 实时监控SQL
- NOIP2017考后总结
- python学习之路:语法基础
- ELK-Logstash(1)
- C++学习系列(四)——String使用
- Linux下安装jdk报Permission denied以及chmod详解