LeetCode/solutions/566. Reshape the Matrix.md

27 lines
1021 B
Markdown
Raw Permalink Normal View History

2018-09-10 13:14:26 +00:00
# [566. Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix/description/)
# 思路
题意就是将一个二维数组按要求reshape成另一个二维数组使得有同样的row-traversing顺序即按照行优先遍历应该得到同样的结果。
用一个count计数然后对原数组遍历一遍将每个元素填到新数组合适的位置即可。
# C++
2019-09-13 15:08:41 +00:00
```C++
2018-09-10 13:14:26 +00:00
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int original_r = nums.size(), original_c = nums[0].size();
if( r * c != original_r * original_c) return nums;
vector<vector<int>>result;
vector<int>one_row;
int count = 0;
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
one_row.push_back(nums[count / original_c][count % original_c]);
count++;
}
result.push_back(one_row);
one_row.clear();
}
return result;
}
};
```