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;
}
};
继续阅读与本文标签相同的文章
上一篇 :
6个小场景告诉你,人工智能手机将怎么改变人类生活
下一篇 :
17个新手常见Python运行时错误
-
开发者必读 · 周报 | 002期
2026-05-19栏目: 教程
-
斩获2019中国金融科技创新大赛金奖,蚂蚁金服mPaaS助力打造超级App生态
2026-05-19栏目: 教程
-
有呀!互联网icp许可证除申请以外有转让的吗?飞起
2026-05-19栏目: 教程
-
Apache Zepplin使用Hive Interpreter查询
2026-05-19栏目: 教程
-
大宗货运如何实现“重去重回”?
2026-05-19栏目: 教程
