当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
Digital IC Design SPI
Navicat run SQL file import data incomplete or import failed
MySQL error 28 and solution
Cloud detection 2020: self attention generation countermeasure network for cloud detection in high-resolution remote sensing images
【堡垒机】云堡垒机和普通堡垒机的区别是什么?
Cinnamon taskbar speed
Milkdown 控件图标
Thread pool reject policy best practices
将数学公式在el-table里面展示出来
存储过程的介绍与基本使用
随机推荐
10 pictures open the door of CPU cache consistency
Mongodb slice summary
Write it down once Net a new energy system thread surge analysis
MySQL error 28 and solution
[etc.] what are the security objectives and implementation methods that cloud computing security expansion requires to focus on?
ESP32 ① 编译环境
Realize the IP address home display function and number home query
高端了8年,雅迪如今怎么样?
Navicat run SQL file import data incomplete or import failed
10 张图打开 CPU 缓存一致性的大门
最佳实践 | 用腾讯云AI意愿核身为电话合规保驾护航
2022-7-7 Leetcode 844.比较含退格的字符串
一文读懂数仓中的pg_stat
Ogre introduction
Final review notes of single chip microcomputer principle
Introduce six open source protocols in detail (instructions for programmers)
Pay close attention to the work of safety production and make every effort to ensure the safety of people's lives and property
PHP - laravel cache
服务器到服务器 (S2S) 事件 (Adjust)
About how appium closes apps (resolved)