1. 程式人生 > >[LeetCode] Reshape the Matrix 矩陣重塑

[LeetCode] Reshape the Matrix 矩陣重塑

ren ati num 我們 資料 call posit tar led

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函數,博主也經常使用matlab,對這個函數還是比較的熟悉的。對於這種二維數組大小重新非配的問題的關鍵就是對應位置的坐標轉換,最直接的辦法就是先把原數組拉直,變成一條直線,然後再組成新的數組。所以這道題我們先判斷給定數組是否能重塑成給定的大小,就是看兩者的元素總數是否相同,直接行數乘以列數即可,然後我們新建一個目標大小的數組,並開始遍歷,對於每個位置,我們先轉為拉直後的一維坐標,然後在算出在原數組中的對應位置賦值過來即可,參見代碼如下:

解法一:

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        int m = nums.size(), n = nums[0].size();
        if (m * n != r * c) return nums;
        vector<vector<int>> res(r, vector<int>(c));
        for (int i = 0; i < r; ++i) {
            for (int j = 0; j < c; ++j) {
                int k = i * c + j;
                res[i][j] = nums[k / n][k % n];
            }
        }
        return res;
    }
};

下面這種方法整體思路和上面沒啥區別,但是只使用了一個循環,直接就是遍歷拉直後的一維數組的坐標,然後分別轉換為兩個二維數組的坐標進行賦值,參見代碼如下:

解法二:

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        int m = nums.size(), n = nums[0].size();
        if (m * n != r * c) return nums;
        vector<vector<int>> res(r, vector<int>(c));
        for (int i = 0; i < r * c; ++i) {
            res[i / c][i % c] = nums[i / n][i % n];
        }
        return res;
    }
};

參考資料:

https://discuss.leetcode.com/topic/87851/java-concise-o-nm-time

[LeetCode] Reshape the Matrix 矩陣重塑