From 841ca649d36a0c3cb65b99b5112b74be9e87041c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=94=90=E6=A0=91=E6=A3=AE?= <14021051@buaa.edu.cn> Date: Mon, 10 Sep 2018 21:14:26 +0800 Subject: [PATCH] Create 566. Reshape the Matrix.md --- 566. Reshape the Matrix.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 566. Reshape the Matrix.md 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; + } +}; +```