leetcode566. Reshape the Matrix

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ns708865818/article/details/88078289

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.

solution1:保存一下原矩阵元素即可。

class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        int m = nums.size();
        int n = nums[0].size();
        if(m*n!=r*c){
            return nums;
        }
        vector<vector<int>> ret(r,vector<int>(c,0));
        vector<int> total_element;
        for(int i =0;i<m;i++){
            for(int j =0;j<n;j++){
                total_element.push_back(nums[i][j]);
            }
        }
        for(int i = 0;i< r;i++){
            for(int j = 0;j<c;j++){
                ret[i][j] = total_element[c*i+j];
            }
        }
        return ret;
        
        
    }
};

猜你喜欢

转载自blog.csdn.net/ns708865818/article/details/88078289