LeetCode/566. Reshape the Matrix.md
2018-09-10 21:14:26 +08:00

27 lines
1018 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [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;
}
};
```