当前位置:网站首页>【 LeetCode 】 566. Reshape the matrix
【 LeetCode 】 566. Reshape the matrix
2022-07-29 15:02:00 【Crispy~】
题目
在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据.
给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数.重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充. 如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵.
示例 1:
输入:mat = [[1,2],[3,4]], r = 1, c = 4
输出:[[1,2,3,4]]
示例 2:
输入:mat = [[1,2],[3,4]], r = 2, c = 4
输出:[[1,2],[3,4]]
提示:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
-1000 <= mat[i][j] <= 1000
1 <= r, c <= 300
题解
forCyclic Violent Transformation
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
//获取初始化参数
int m = mat.size();
int n = mat[0].size();
if(m*n != r*c)//Do not process if the number of matrix elements is not equal
return mat;
vector<vector<int>> result;
int cx=0;//计数,每一行c个元素
vector<int> tmp(c);//存储一行数据
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
tmp[cx++] = mat[i][j];
if(cx==c)//tmpWhen a row is full, it is pushed into a new matrix
{
cx=0;
result.push_back(tmp);
}
}
}
return result;
}
};
矩阵的第i行jThe elements of the column are subscripted as :i*m+j
所以下标为index时,i=index/m,j=index%m
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
int m = mat.size();
int n = mat[0].size();
if(m*n != r*c)
return mat;
vector<vector<int>> result(r,vector<int>(c));
for(int i=0;i<m*n;i++)
{
result[i/c][i%c] = mat[i/n][i%n];
}
return result;
}
};
边栏推荐
- 为什么字符串使用final关键字
- 【C语言】AI三子棋的成长之路
- 基于C语言实现的LL(1)分析
- MySQL 是如何实现 ACID 的?
- Linux安装MySQL(超详细)
- 国产手机将用户变成它们的广告肉鸡,难怪消费者都买iPhone了
- Programmers are a group with a high incidence of occupational diseases. Don’t be naive to think that it’s just as simple as being bald.
- 关于内部类
- Domestic mobile phones turn users into their advertising broilers, no wonder consumers are buying iPhones
- 交叉编译工具链的安装和配置过程
猜你喜欢

数字孪生万物可视 |联接现实世界与数字空间

【Postman】下载与安装(新手图文教程)

MySQL索引常见面试题(2022版)

Map遍历 key-value 的4种方法

EA&UML日拱一卒-活动图::CallOperationAction(续)

AVH部署实践 (一) | 在Arm虚拟硬件上部署飞桨模型

测试日报怎么写 ?

Introduction to several methods of making custom welcome interface on Weiluntong touch screen

基于C语言仿真实现的粒子火焰系统

WOLFLAB一方老师为什么要写网络虚拟化《VMware NSX-T卷2》路由架构-2
随机推荐
关于数字化转型 你需要知道的八项指导原则
Interfaces and Abstractions
Based on domestic, link global | schneider electric "industrial SI alliance partners hand in hand" to the industry in the future
从一道面试题说起:GET 请求能传图片吗?
深开鸿:万物智联的大江上,升起一轮开源鸿蒙月
软件测试架构师的工作日常
kubernetes cks strace etcd
暴力递归到动态规划 02 (绝顶聪明的人的纸牌游戏)
工作效率-十五分钟让你快速学习Markdown语法到精通排版实践备忘
A review of deep learning for beginners!
【C语言】AI三子棋的成长之路
EA&UML日拱一卒-活动图::CallOperationAction(续)
第4章_2——视图的使用
如何编辑CAD图库里的图纸
The raised platform system based on JSP&Servlet implementation
生鲜赛道溃败中存活的本来生活,纠结生存
自定义fingerprint特征
没遇到过这三个问题都不好意思说用过Redis
正则、grep/egrep、sed、awk
2022杭电多校第三场