当前位置:网站首页>566. 重塑矩阵
566. 重塑矩阵
2022-07-07 11:38:00 【yitahutu79】
在 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
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>> arr(r, vector<int>(c));
for (int i = 0; i < m * n; i++) {
arr[i/c][i%c] = mat[i/n][i%n];
}
return arr;
}
};
边栏推荐
猜你喜欢
随机推荐
Ways to improve the performance of raspberry pie
QQ medicine, Tencent ticket
My "troublesome" subordinates after 00: not bad for money, against leaders, and resist overtime
Read PG in data warehouse in one article_ stat
Error lnk2019: unresolved external symbol
shell 批量文件名(不含扩展名)小写改大写
Talk about pseudo sharing
Isprs2021/ remote sensing image cloud detection: a geographic information driven method and a new large-scale remote sensing cloud / snow detection data set
将数学公式在el-table里面展示出来
Getting started with cinnamon applet
Ogre introduction
error LNK2019: 无法解析的外部符号
Ogre入门尝鲜
Flink | 多流转换
记一次 .NET 某新能源系统 线程疯涨 分析
1. Deep copy 2. Call apply bind 3. For of in differences
Data refresh of recyclerview
Ikvm of toolbox Net project new progress
1、深拷贝 2、call apply bind 3、for of for in 区别
[learning notes] zkw segment tree