当前位置:网站首页>Leetcode 笔记 566. 重塑矩阵
Leetcode 笔记 566. 重塑矩阵
2022-07-28 12:07:00 【Lyrig~】
题目描述
题目连接
在 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>>& nums, int r, int c) {
int m = nums.size();
int n = nums[0].size();
if (m * n != r * c) {
return nums;
}
vector<vector<int>> ans(r, vector<int>(c));
for (int x = 0; x < m * n; ++x) {
ans[x / c][x % c] = nums[x / n][x % n];
}
return ans;
}
};
注意
学习一下vector的初始化方式,这个很重要,能够节省时间。
边栏推荐
- Unity—“合成大西瓜”小游戏笔记
- 我抄底了被清算的NFT,却被OpenSea上了锁
- QT signal and slot mechanism (detailed)
- How many times can the WordPress user name be changed? Attach the method of changing user name
- [FPGA]: ISE generates MCS file and burning process
- 黑猫带你学eMMC协议第24篇:eMMC的总线测试程序详解(CMD19 & CMD14)
- 面试必问,敲重点!讲一下 Android Application 启动流程及其源码?
- 04 pyechars geographic chart (example code + effect diagram)
- Full disclosure! Huawei cloud distributed cloud native technology and Practice
- Transaction of MySQL underlying principle (2)
猜你喜欢

Huawei cloud Gao Hongxia: CBC microservice code Reconstruction & independent release practice

Array, string de duplication

Understanding of vite2

拥有游戏的一部分,写在我的世界禁用NFT之后

2020-12-13
![[embedded C foundation] Part 2: binary conversion and BCD coding](/img/12/d9a42cf7b4dc177d00e5dc3cdaa5cd.png)
[embedded C foundation] Part 2: binary conversion and BCD coding

Aragon创建DAO polygon BSC测试网

SSH port forwarding (Tunneling Technology)

Led aquarium lamp touch chip-dlt8t02s-jericho

Margin calculation
随机推荐
企业数字化本质
【嵌入式C基础】第2篇:进制转换与BCD编码
Black cat takes you to learn EMMC Protocol Part 26: hardware reset operation of EMMC (h/w reset)
Databinding+LiveData轻松实现无重启换肤
.net for subtraction, intersection and union of complex type sets
Shenwenbo, researcher of the Hundred Talents Program of Zhejiang University: kernel security in the container scenario
2020-12-13
UV germicidal lamp chip dlt8p65sa Jericho
管理区解耦架构见过吗?能帮客户搞定大难题的
[June 28 event preview] low code Summit
Kotlin是如何帮助你避免内存泄漏的?
Smart touch screen LCD bathroom mirror light touch chip-dlt8t02s-jericho
【C语言易错点】第4篇:结构体在内存中存储规则详讲
Leetcode daily question (2196. create binary tree from descriptions)
[error prone points of C language] Part 4: detailed rules for storing structures in memory
Compare the new and old data to find the added and deleted ones
How to design a second kill system?
黑猫带你学eMMC协议第26篇:eMMC的硬件复位操作(H/W reset)
面试必问,敲重点!讲一下 Android Application 启动流程及其源码?
Unity—“合成大西瓜”小游戏笔记