LeetCode - 566. Reshape the Matrix (C++) O(n)
2017-08-26 06:43
507 查看
1. 题目大意
根据给定矩阵,重塑一个矩阵,r是所求矩阵的行数,c是所求矩阵的列数。如果给定矩阵和所求矩阵的数据个数不一样,那么返回原矩阵。否则,重塑矩阵。其中两个矩阵中的数据顺序不变(先行后列)。
2. 思路
由于矩阵中数据顺序不变,因此我们考虑按顺序做。原矩阵中的第i行第j列(从0开始)的数据可以记为第k个数,其中k=i*(原矩阵中的列数)+j。对应的是新产生的矩阵中的第k/c行,k%c列的元素。一一赋值。这题的关键是要小心数组的边界,正确找到对应的位置。
3. 代码
根据给定矩阵,重塑一个矩阵,r是所求矩阵的行数,c是所求矩阵的列数。如果给定矩阵和所求矩阵的数据个数不一样,那么返回原矩阵。否则,重塑矩阵。其中两个矩阵中的数据顺序不变(先行后列)。
2. 思路
由于矩阵中数据顺序不变,因此我们考虑按顺序做。原矩阵中的第i行第j列(从0开始)的数据可以记为第k个数,其中k=i*(原矩阵中的列数)+j。对应的是新产生的矩阵中的第k/c行,k%c列的元素。一一赋值。这题的关键是要小心数组的边界,正确找到对应的位置。
3. 代码
class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int total = r*c, originr = nums.size(), originc = nums[0].size(); if(total != (originr*originc)) return nums; vector<vector <int> > res(r ,vector<int>(c)); for(int k = 0; k < total; k++) res[k / c][k % c] = nums[k / originc][k % originc]; return res; } };
相关文章推荐
- 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(Easy)
- LeetCode-566-Reshape the Matrix-E
- [Leetcode] 566. Reshape the Matrix 解题报告
- [LeetCode]566. Reshape the Matrix(重塑矩阵)
- 【LeetCode】566. Reshape the Matrix(重塑矩阵)
- LeetCode566——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 566. Reshape the Matrix (Easy)
- Array-leetcode 566 Reshape the Matrix
- Leetcode 566. Reshape the Matrix 矩阵变形(数组,模拟,矩阵操作)
- leetcode 566. Reshape the Matrix 重塑矩阵