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.
  • 题目大意&解题思路

题目的意思主要是输入一个二维数组,将其转换成【c行 r列】的新二维数组, c * r 要等于原数组的单个元素个数,否则返回原数组。 

首先想到的解法就是先将原来的二维数组转换成一维数组,然后根据c和r的值,依次将一维数组的元素依次push到结果数组之中。

  • 解法一 

vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        
        int n = 0;
        vector<int> new_nums;                
        vector<vector<int>> res;
        
        /*将二维数组变成一维数组*/
        for( int i = 0 ; i < nums.size(); i++ ){
            for( int j = 0; j < nums[i].size(); ++j ){
                new_nums.push_back(nums[i][j]);
            }    
        }
        
        if ( r*c != new_nums.size() ){
            return nums;            
        }

        /*两个for循环将new_nums数组按照c和r的值转换成新数组res*/
        for( int i = 0; i < r; ++i ){
            vector<int> temp_res;            
            for( int j = 0; j < c; ++j ){
                temp_res.push_back(new_nums[n++]);
            }          
            res.push_back(temp_res);
            
        }

        return res;
        
    }
  • 实验结果一

结果不是很好,只beat 12.39%。

  • 解法二

解法一的缺点就是首先将输入的二维数组转换成一维数组,浪费时间,另外两个for循环增加了时间复杂度。考虑能不能不转换原始数组,另外用一个for循环完成。

vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        
        int n = 0;

        vector< vector<int> > res(r, vector<int>(c) );      /*根据c和r创建结果数组*/
        
        int old_col = nums[0].size();
        int old_row = nums.size();
        
        if( c * r != old_col * old_row)
            return nums;
        
        /*根据i和行列的取余和取模判断在数组中的位置*/
        for( int i = 0; i < c * r; ++i ){
            res[i/c][i%c] = nums[i/old_col][i%old_col];
        }

        return res;
        
    }
  • 实验结果二

猜你喜欢

转载自blog.csdn.net/h792746371/article/details/82823634