1. 程式人生 > >Leetcode刷題記錄——566. Reshape the Matrix

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;
        
    }
  • 實驗結果二