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.

 

要完成的函数:

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

说明:

1、这道题就是让我们实现matlab中的reshape函数。给定一个二维的vector,以及转换之后矩阵的行数和列数。如果由于给定的行数和列数的原因而不能转换,那么返回原vector。如果可以,那么返回转换之后的vector。

2、首先我们由给定vector得到原行数和原列数,如果它们的积不等于新行数和新列数的积,那么返回原本vector。

如果相等,那么下一步我们定义一个新的二维vector,写一个双重循环,计算原vector中的每一个元素在新vector中的位置,放进去。

思路清晰,我们可以构造如下代码:

    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。

原文地址:https://www.cnblogs.com/chenjx85/p/8985399.html