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 positiveintegers 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.
Example 1:
Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[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 = 4 Output: [[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.
思路:
1.判断符不符合要求
2.将原始矩阵复制到一个1*n的矩阵里。
3.从1*n的矩阵里取值赋值给r*c矩阵
#pragma once
#include <iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
//判断符不符合reshape的要求
if (nums.size()*nums[0].size() != r * c)
{
return nums;
}
int t = 0;
vector <int> temp;
vector <vector <int>> reshape;
//把矩阵变成1*n
for (int i = 0; i < nums.size(); i++)
{
for (int j = 0; j < nums[0].size(); j++)
{
temp.push_back(nums[i][j]);
}
}
//根据r,c将矩阵组成r行c列
for (int i = 0; i < r; i++)
{
vector <int> temp2;
for (int j = 0; j < c; j++)
{
temp2.push_back(temp[t++]);
}
reshape.push_back(temp2);
}
return reshape;
}
};