566. Reshape the Matrix
来源:互联网 发布:后端用java还是php 编辑:程序博客网 时间:2024/06/05 01:15
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 columnnumber 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.
Example 1:
Input: nums = [[1,2], [3,4]]r = 1, c = 4Output: [[1,2,3,4]]Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input: nums = [[1,2], [3,4]]r = 2, c = 4Output: [[1,2], [3,4]]Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
- The height and width of the given matrix is in range [1, 100].
- The given r and c are all positive.
method1:
class Solution {public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int nr = nums.size(),nc=nums[0].size(); vector<vector<int>>res = vector<vector<int>>(r, vector<int>(c)); int numssize = nr*nc; if(numssize!=r*c) return nums; for(int i = 0;i<numssize;i++){ res[i/c][i%c] = nums[i/nc][i%nc]; } return res; }};
class Solution {public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int size = nums.size() * nums[0].size(); if(size != r * c) return nums; vector<vector<int>> mat(r); for(auto& row: mat){ row.resize(c); } for(int i = 0; i < nums.size(); i++){ int base = i * nums[0].size(); for(int j = 0; j < nums[0].size(); j++){ int index = base + j; mat[index/c][index%c] = nums[i][j]; } } return mat; }};
遍历方式不同
阅读全文
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
- time stamp convert tools 1.0.0.1 on vs2010
- 04 局部变量的空间分配及栈回收重用之汇编分析
- SVN的使用一:TortoiseSVN的下载安装
- cookie详解
- Git版本库相关操作
- 566. Reshape the Matrix
- HDU4909 String
- 教你如何修改wordpress模版技巧分享
- 树、森林与二叉树的转换和哈夫曼树
- 哈希表的使用-11-散列1 电话聊天狂人
- 【python】用selenium webdriver做简单的表格提交
- QT学习笔记(5)对话框(2)
- MLP(多层神经网络)介绍
- Larbin学习小结