算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
今天和大家聊的问题叫做 重塑矩阵,我们先来看题面:
https://leetcode-cn.com/problems/reshape-the-matrix/
In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.
在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据。
给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数。
重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。
如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。
示例

解题
https://www.jianshu.com/p/780a154cdb63
思路很朴素,首先判断能不能转换,不能转换的话,就直接结束了。
能转换的话就是首先申请一个r维向量。开始还有些想当然,没申请就用,然后测试的时候就越界了。申请了两个 int 变量去记录当前转换到哪一行哪一列了。接下来就一路遍历挨个转换。
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
if (nums.size()*nums[0].size() != r*c) {
return nums;
}
vector<vector<int> > num(r);
int rl=0, cl=0;
for (int i = 0; i < nums.size(); ++i) {
for (int j = 0; j < nums[0].size(); ++j) {
if (cl < c) {
num[rl].push_back(nums[i][j]);
cl++;
} else {
cl = 0;rl++;
num[rl].push_back(nums[i][j]);
cl++;
}
}
}
return num;
}
};
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。
上期推文:

1225

被折叠的 条评论
为什么被折叠?



