Leetcode刷题(23)
来源:互联网 发布:报表制作软件 编辑:程序博客网 时间:2024/05/17 17:59
In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.
You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.
The reshaped matrix need to 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.
Example 1:
Input: nums = [[1,2], [3,4]]r = 1, c = 4Output: [[1,2,3,4]]Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input: nums = [[1,2], [3,4]]r = 2, c = 4Output: [[1,2], [3,4]]Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
- The height and width of the given matrix is in range [1, 100].
- The given r and c are all positive.
Subscribe to see which companies asked this question.
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
vector<int> a;
vector<vector<int>> b(r, vector<int>(c));
if(r*c != nums.size()*nums[0].size()) {
return nums;
}
for(int i=0; i<nums.size(); i++) {
for(int j=0; j<nums[0].size(); j++) {
a.push_back(nums[i][j]);
}
}
int count = 0;
for(int i=0; i<r; i++) {
for(int j=0; j<c; j++) {
b[i][j] = a[count];
count++;
}
}
return b;
}
};
- Leetcode刷题(23)
- LeetCode刷题(23)
- 【leetcode】leetcode 刷题 笔记 (不定期更新)
- leetcode刷题(Python)
- LeetCode刷题(1)
- LeetCode刷题(2)
- LeetCode刷题(3)
- LeetCode刷题(废弃)
- LeetCode刷题(FizzBuzz)
- Leetcode刷题(1)
- Leetcode刷题(2)
- Leetcode刷题(3)
- Leetcode刷题(4)
- Leetcode刷题(5)
- Leetcode刷题(6)
- Leetcode刷题(7)
- Leetcode刷题(13)
- Leetcode刷题(17)
- c/c++基础(一)
- 【CodeForces 803A】Maximal Binary Matrix(模拟)
- Ubuntu把家目录(home)文件夹修改成英文
- python机器学习实战3:朴素贝叶斯分类器
- bzoj4800: [Ceoi2015]Ice Hockey World Championship
- Leetcode刷题(23)
- db2存储过程小例子
- Java IO流 读写
- 上传图文消息内的图片获取URL【订阅号与服务号认证后均可用】
- Linux操作系统学习_4
- svn 导入项目
- java中锁的深入理解(一)
- RecyclerView多条目
- 第十一 系统恢复技术