566.Reshape the Matrix
来源:互联网 发布:高压清洗机品牌 知乎 编辑:程序博客网 时间:2024/06/04 17:57
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the 'reshape' operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
改变矩阵的形状
方法:一个一个复制,时间复杂度O(nm),额外空间复杂度O(1)
class Solution {public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int ro=nums.size(); if(ro==0) return nums; int co=nums[0].size(); if(r*c!=ro*co) return nums; vector<vector<int>> res(r,vector<int>(c,0)); int io=0,jo=0;//原数组的行和列标号 for(int i=0;i<r;i++) { for(int j=0;j<c;j++) { if(jo==co)//当一行复制完,移动到下一行 { jo=0; io++; } res[i][j]=nums[io][jo++]; } } return res; }};
0 0
- 566. Reshape the Matrix
- 566.Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- 566. Reshape the Matrix
- Java 8新特性
- 分治算法主定理
- 用servlet实现微博小程序----注册
- HDOJ 2021 发工资咯:)
- code[vs] 1017乘积最大
- 566.Reshape the Matrix
- ssm整合之四 分页
- ajax使用formdata上传文件流
- 微信小程序跳转无效
- 失误的总结
- Android之自定义View以及画一个时钟
- 【技能库】--获取当天的0点和23点59分59秒(192)
- 12. Integer to Roman
- 多线程中不用start()而用run()的后果