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:

  1. The height and width of the given matrix is in range [1, 100].
  2. The given r and c are all positive.

粗略翻譯:

在MATLAB中有一個很好用的方法叫 「reshape」,該方法可將一矩陣重塑為size不同的新矩陣,但仍能保留原始資料。

我們的程式目的是將目標矩陣依照row跟column的要求reshape為一個新矩陣,

如果給定的row跟column無法reshape為一個完整的新矩陣,則返回原始矩陣。

另外題目有兩條規定:

  1. 矩陣的height跟width會介於1到100之間
  2. r跟c一定是正數

解法:

首先先檢查給定的r跟c是否能組成一個新的且合法的矩陣,如果不行則直接返回原始舉陣

如果可以則繼續下一步,先依照r跟c來new新的矩陣

接著就依照原始矩陣的順序依序填滿新矩陣即可

 

 


網站:http://wp.mlab.tw/
GitHub:https://github.com/yoll522/LeetCode
程式碼:https://github.com/yoll522/LeetCode/tree/master/537.%20Complex%20Number%20Multiplication

Leave a Reply

你的電子郵件位址並不會被公開。 必要欄位標記為 *