当前位置:网站首页>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;
}
};
边栏推荐
- Xshell connection server changes key login to password login
- [etc.] what are the security objectives and implementation methods that cloud computing security expansion requires to focus on?
- 【黑马早报】华为辟谣“军师”陈春花;恒驰5预售价17.9万元;周杰伦新专辑MV 3小时播放量破亿;法华寺回应万元月薪招人...
- RealBasicVSR测试图片、视频
- Talk about pseudo sharing
- Read PG in data warehouse in one article_ stat
- MongoDB的用户管理总结
- Indoor ROS robot navigation commissioning record (experience in selecting expansion radius)
- LeetCode简单题分享(20)
- ESP32构解工程添加组件
猜你喜欢
Ways to improve the performance of raspberry pie
靠卖概念上市,认养一头牛能走多远?
LED light of single chip microcomputer learning notes
实现IP地址归属地显示功能、号码归属地查询
1. Deep copy 2. Call apply bind 3. For of in differences
Redis只能做缓存?太out了!
Japanese government and enterprise employees got drunk and lost 460000 information USB flash drives. They publicly apologized and disclosed password rules
OSI seven layer model
分布式事务解决方案
Talk about pseudo sharing
随机推荐
DID登陆-MetaMask
How to make the new window opened by electorn on the window taskbar
LED light of single chip microcomputer learning notes
实现IP地址归属地显示功能、号码归属地查询
一文读懂数仓中的pg_stat
Navicat运行sql文件导入数据不全或导入失败
[QNX hypervisor 2.2 user manual]6.3.4 virtual register (guest_shm.h)
Detr introduction
最佳实践 | 用腾讯云AI意愿核身为电话合规保驾护航
【面试高频题】难度 2.5/5,简单结合 DFS 的 Trie 模板级运用题
存储过程的介绍与基本使用
MongoDB命令汇总
ESP32系列专栏
About how appium closes apps (resolved)
[learning notes] segment tree selection
[dark horse morning post] Huawei refutes rumors about "military master" Chen Chunhua; Hengchi 5 has a pre-sale price of 179000 yuan; Jay Chou's new album MV has played more than 100 million in 3 hours
How far can it go to adopt a cow by selling the concept to the market?
DETR介绍
MongoDB的用户管理总结
Simple and easy-to-use code specification