mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
27 lines
1018 B
Markdown
27 lines
1018 B
Markdown
![]() |
# [566. Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix/description/)
|
|||
|
# 思路
|
|||
|
题意就是将一个二维数组按要求reshape成另一个二维数组使得有同样的row-traversing顺序,即按照行优先遍历应该得到同样的结果。
|
|||
|
用一个count计数,然后对原数组遍历一遍将每个元素填到新数组合适的位置即可。
|
|||
|
# C++
|
|||
|
```
|
|||
|
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;
|
|||
|
}
|
|||
|
};
|
|||
|
```
|