1.问题描述:数组
在MATLAB中,有一个很是有用的函数 reshape
,它能够将一个矩阵重塑为另外一个大小不一样的新矩阵,但保留其原始数据。函数
给出一个由二维数组表示的矩阵,以及两个正整数r
和c
,分别表示想要的重构的矩阵的行数和列数。spa
重构后的矩阵须要将原始矩阵的全部元素以相同的行遍历顺序填充。code
若是具备给定参数的reshape
操做是可行且合理的,则输出新的重塑矩阵;不然,输出原始矩阵。blog
示例 1:io
输入: nums = [[1,2], [3,4]] r = 1, c = 4 输出: [[1,2,3,4]] 解释: 行遍历nums的结果是 [1,2,3,4]。新的矩阵是 1 * 4 矩阵, 用以前的元素值一行一行填充新矩阵。
示例 2:class
输入: nums = [[1,2], [3,4]] r = 2, c = 4 输出: [[1,2], [3,4]] 解释: 没有办法将 2 * 2 矩阵转化为 2 * 4 矩阵。 因此输出原矩阵。
注意:重构
2.解决过程:遍历
class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int row=nums.size(); int column=nums[0].size(); if(row*column<r*c) return nums; vector<vector<int>> result(r); for(int i=0,m=0,n=0;i<r;i++) { for(int j=0;j<c;j++) { result[i].push_back(nums[m][n]); if(n<column-1) n++; else { m++; n=0; } } } return result; } };