leetcode-566-Reshape the Matrix

Topic description:

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.

 

Function to be done:

vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) 

 

illustrate:

1. This question is to let us implement the reshape function in matlab. Given a two-dimensional vector, and the number of rows and columns of the transformed matrix. If the conversion cannot be done due to the given number of rows and columns, the original vector is returned. If so, return the converted vector.

2. First, we get the original number of rows and the original number of columns from the given vector. If their product is not equal to the product of the new number of rows and the number of new columns, then return the original vector.

If they are equal, then next step we define a new two-dimensional vector, write a double loop, calculate the position of each element in the original vector in the new vector, and put it into it.

With a clear idea, we can construct the following code:

    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) 
    {
        int orow=nums.size();//初始的行数和列数
        int ocol=nums[0].size();
        if(orow*ocol!=r*c)
            return nums;
        vector<int> resc(c);
        vector<vector<int>>res(r,resc);
        int tr,tc,index;//转换后的行数和列数
        for(int i=0;i<orow;i++)
        {
            for(int j=0;j<ocol;j++)
            {
                index=i*ocol+j;
                tr=index/c;
                tc=index%c;
                res[tr][tc]=nums[i][j];
            }
        }
        return res;
    }

上述代码实测40ms,beats 82.30% of cpp submissions。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325212444&siteId=291194637