In MATLAB, there is a very useful function 0 that remolds an M x N matrix into another new matrix of a different size (R x C), but preserves its original data.

You are given an M x N matrix represented by a two-dimensional array mat, and two positive integers r and C, representing the number of rows and columns of the matrix you want to reconstruct.

The reconstructed matrix requires that all elements of the original matrix be filled in the same row traversal order.

0 0 If the 0 0 operation with the given parameters is 0 0 0 0 0 Otherwise, output the original matrix.

 

Example 1:

Input:

Mat = [[1,2],[3,4]], r = 1, c = 4

Output:

[[1, 2, 3, 4]]

Example 2:

Input:

Mat = [[1,2],[3,4]], r = 2, c = 4

Output:

[[1, 2], [3, 4]]

Tip:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • -1000 <= mat[i][j] <= 1000
  • 1 <= r, c <= 300

Code:

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& mat, int r, int c) {
        int n = mat.size(a);int m = mat[0].size(a);if(m * n ! = r * c )return mat ;
        vector<vector<int>> ans(r , vector<int>(c));
        for(int i = 0 ; i < m*n ; i ++ )
            ans[i / c][i % c] = mat[i / m][i % m];
        returnans; }};Copy the code

Ideas:

For a two-dimensional array of m rows, n columns, and row and column subscripts numbered from 0, we map each element (I, j) to the integer field in such a way that they correspond to each integer in [0,mn] in row first order. Visually, we “flatten” this two-dimensional array into a one-dimensional array. For those of you who know anything about machine learning, this is the Flatten operation.

The mapping is:

(I, j) - > I * n + j

Similarly, we can map the integer x back to its subscript in the matrix, i.e

i = x / n
j = x % n
Copy the code

Where/stands for integer division, % stands for modular operation.

So what they want us to do is:

Map the two-dimensional array NUMS to a one-dimensional array;

Map this one-dimensional array back to a two-dimensional array of rows R and columns C.

We can of course use a one-dimensional array directly for the transition, but we can also get the remodeling matrix for row R and column C directly from the two-dimensional array NUMS:

Let numS itself be m rows and n columns if MN! = rc, then the two contain different numbers of elements, so they cannot be reshaped;

Otherwise, for x∈[0,mn), the corresponding subscript of the x-th element in NUMs is (x/n,x % n), and the corresponding subscript in the new remodeling matrix is (x/c,x % c). We can simply assign the value.

Complexity analysis:

  • Time complexity: O(RC). The time complexity here is the time complexity if the remolding matrix is successful, otherwise when mn =rc, the C++ language returns a copy of the original array, which essentially requires O(mn) time complexity.

  • Space complexity: O(1). The space complexity here does not include the space required for the returned remodeling matrix.