1. 程式人生 > >LeetCode-566. Reshape the Matrix 重塑矩陣

LeetCode-566. Reshape the Matrix 重塑矩陣

一、問題描述
In MATLAB, there is a very useful function called ‘reshape’, which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the ‘reshape’ operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.
二、思路和程式
思路:首先需要判斷能否構造出給定的行列數,即構造後的矩陣中的元素個數要和給定的nums中的元素個數一致。判斷完之後,按行遍歷nums,將其元素存放到vectormarix中,並記下marix中的元素個數n,當n % c == 0,即n是要構造矩陣的列數的倍數時,將marix存放到 vector<vector>number中,最後生成的 number就是重塑後的矩陣。
程式(C++程式碼):
vector<vector> matrixReshape(vector<vector>& nums, int r, int c)
{
vector<vector>number;
vectormarix;
int row = nums.size();
int col = nums[0].size();
int n = 0;
if (rc != row

col)
return nums;
for (int i = 0; i < nums.size(); i++)
{
for (int j = 0; j < nums[i].size(); j++)
{
marix.push_back(nums[i][j]);
n++;
if (n % c == 0)
{
number.push_back(marix);
marix.clear();
}
}
}
return number;
}
三、執行效果
在這裡插入圖片描可見述
從圖中可以看出,程式碼效果還是不錯的。