Leetcode 566. Reshape the Matrix 矩阵变形(数组,模拟,矩阵操作)
2018-02-23 19:57
731 查看
Leetcode 566. Reshape the Matrix 矩阵变形(数组,模拟,矩阵操作)
题目描述
在MATLAB中,reshape是一个非常有用的函数,它可以将矩阵变为另一种形状且保持数据不变。
已知一个由二维数组表示的矩阵,和两个正整数r(行),c(列),将这个二维数组变换为r*c的矩阵。
如果不能由原矩阵转换为r*c的矩阵就输出原矩阵,否则输出转换后的矩阵。
测试样例
Input: nums = [[1,2], [3,4]] r = 1, c = 4 Output: [[1,2,3,4]] nums = [[1,2], [3,4]] r = 2, c = 4 Output: [[1,2], [3,4]] Explanation: 原2*2矩阵不能变换为2*4矩阵,所以原样输出。
详细分析
考虑将[[1,2],[3,4]]转换为1*4的[1,2,3,4]。首先我们需要两个循环,将原矩阵数据填入新矩阵
for(int i=0;i<r;i++){ for(int k=0;k<c;k++){ ... } }
这里的难点是坐标的变换。它们对照关系如下:
newArr[0][0]=>oldArr[0][0] newArr[0][1]=>oldArr[0][1] newArr[0][3]=>oldArr[1][0] newArr[0][4]=>oldArr[1][1]
这里我们考虑一种中间形式,先把新二维坐标转换为一维坐标,再将一维坐标转换为旧的二维坐标。比如,当我们填入newArr[0][3]时,它的一维坐标是0*c(新矩阵列数)+3,即3,然后3转化为旧的二维坐标就是
old[3/原二维列数][3%原二维列数]
代码实现
class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { //corner case for empty 2-dimension array if(nums.size()==0){ return nums; } if(nums[0].size()==0){ return nums; } //illegal case if(nums.size()*nums[0].size()!=r*c){ return nums; } std::vector<std::vector<int>> dv; for(int i=0;i<r;i++){ std::vector<int> v; for(int k=0;k<c;k++){ int p=i*c+k; int idx1=p/nums[0].size(); int idx2=p%nums[0].size(); v.push_back(nums[idx1][idx2]); } dv.push_back(v); } return dv; } };
相关文章推荐
- Leetcode 566. Reshape the Matrix 矩阵变形(数组,模拟,矩阵操作)
- leetcode -- 566. Reshape the Matrix 【矩阵转换 + 不同数组下标映射】
- leetcode 566. Reshape the Matrix 重塑矩阵
- LeetCode 566. Reshape the Matrix (重塑矩阵)
- LeetCode | 566. Reshape the Matrix 简单矩阵循环题
- 【LeetCode】566. Reshape the Matrix(重塑矩阵)
- leetcode 数组array之566. Reshape the Matrix
- Leetcode 566 Reshape the Matrix 将数组转换为我们想要的行和列
- LeetCode-566:Reshape the Matrix (矩阵整型)-- easy
- [LeetCode]566. Reshape the Matrix(重塑矩阵)
- LeetCode - 566. Reshape the Matrix (C++) O(n)
- [Leetcode] 566. Reshape the Matrix 解题报告
- [LeetCode] Reshape the Matrix 重塑矩阵
- Reshape the Matrix 矩阵变形
- leetcode 566 Reshape the Matrix
- leetcode 566: Reshape the Matrix
- 566. Reshape the Matrix重塑矩阵
- 【LeetCode】566 Reshape the Matrix
- LeetCode:566. Reshape the Matrix
- leetcode Reshape the Matrix 重置矩阵