diff --git a/566. Reshape the Matrix.md b/566. Reshape the Matrix.md new file mode 100644 index 0000000..c1f4c6d --- /dev/null +++ b/566. Reshape the Matrix.md @@ -0,0 +1,26 @@ +# [566. Reshape the Matrix](https://leetcode.com/problems/reshape-the-matrix/description/) +# 思路 +题意就是将一个二维数组按要求reshape成另一个二维数组使得有同样的row-traversing顺序,即按照行优先遍历应该得到同样的结果。 +用一个count计数,然后对原数组遍历一遍将每个元素填到新数组合适的位置即可。 +# C++ +``` +class Solution { +public: + vector> matrixReshape(vector>& 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>result; + vectorone_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; + } +}; +```