当前位置:网站首页>【 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;
}
};
边栏推荐
猜你喜欢
随机推荐
国产手机将用户变成它们的广告肉鸡,难怪消费者都买iPhone了
基于C语言实现的LL(1)分析
什么是异构计算
关于内部类
【yolov7系列二】正负样本分配策略
带你搞懂 Redis 中的两个策略
图斑自上而下,自左而右顺序编码,按照权属单位代码分组,每组从1开始编码
EA&UML日拱一卒-活动图::Feature和StuctualFeature
【LeetCode】217. 存在重复元素
全面质量管理理论
《外太空的莫扎特》
升级openssl1.1.1(mix2s哪个版本不断流)
Couldn‘t create temporary file /tmp/apt.conf.uko4Kd for passing config to apt-key
【Postman】Download and installation (novice graphic tutorial)
EA&UML日拱一卒-活动图::StartClassifierBehavior和StartObjectBehavior
即刻体验 | 借助 CTS-D 进一步提升应用设备兼容性
kubernetes中正strace etcd
如何使用SparkSQL做一些简单的数据分析和可视化展示?
Google Play 政策更新 | 2022 年 7 月
About inner classes









