当前位置:网站首页>【LeetCode】566. 重塑矩阵
【LeetCode】566. 重塑矩阵
2022-07-29 14:31:00 【酥酥~】
题目
在 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
题解
for循环暴力转换
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;
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)//tmp存满一行就压入新矩阵中
{
cx=0;
result.push_back(tmp);
}
}
}
return result;
}
};
矩阵的第i行j列的元素下标为: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;
}
};
边栏推荐
- 【IIC通信】Chap.2 (I2C)IIC协议的特点;为什么IIC需要开漏输出、上拉电阻?
- arcgis中编码方式改变引起的shp文件乱码、字符截断问题处理
- 建议尽快优化搜索体验
- C语言 4:汇编语言指令介绍
- RAMAN 中 OPTIMIZATION 优化选项的作用
- Zhaoqi Technology creates a platform for overseas high-level talent introduction, corporate project docking, and event roadshows
- 4519. 正方形数组的数目
- 威纶通触摸屏制作自定义欢迎界面的几种方法介绍
- A review of deep learning for beginners!
- 2022年了!还在用定时器实现动画?赶紧试试requestAnimationFrame吧!
猜你喜欢
【IIC通信】Chap.1(I2C)IIC通信原理、IIC读写时序详解
工作效率-十五分钟让你快速学习Markdown语法到精通排版实践备忘
【堡垒机小知识】硬件堡垒机是什么意思?其与云堡垒机有什么区别?
工业设备数字孪生技术,解决方案系统平台案例
文本处理之xml
Domestic mobile phones turn users into their advertising broilers, no wonder consumers are buying iPhones
一篇适合新手的深度学习综述!
力扣之顺序表
苹果官方降价的原因找到了,它也面临销量下滑乃至出现库存问题
力扣每日一题-第45天-682. 棒球比赛
随机推荐
测试时间的评估:开发时间的1/3~1/2
Principles Of Mathematical Analysis, Third Edition免费下载地址
嵌入式开发经验分享,把学习当作一种兴趣
C语言 3:常量和变量,顺序语句,选择语句,循环语句,作用域和生存期
基于Flink CDC打通数据实时入湖
【ArcGIS微课1000例】0030:ArcGIS利用MXD doctor工具分析并修复mxd地图文档
EA&UML日拱一卒-活动图::Object actions(续)
Google Cloud X Kyligence|如何从业务视角管理数据湖?
一篇适合新手的深度学习综述!
超好用的PC端录屏软件推荐
全球级的分布式数据库 Google Spanner原理 热:报错
Chinese Internet technology companies were besieged by wolves. Google finally suffered a severe setback and its profits fell sharply. It regretted promoting the development of Hongmeng...
ST表(动态规划倍增思路离线维护区间极值问题)
部门例会上做测试分享,不知道分享什么内容?
求教一下 现在最新版的flinkcdc能获取到oracle的ddl变更信息吗?
数据库mysql的执行顺序(sql语句大全实例教程)
Offensive EA&UML day arch - activity diagram: : Variable Actions (continue)
《外太空的莫扎特》
【yolov7系列二】正负样本分配策略
A review of deep learning for beginners!