566.Reshape the Matrix

来源:互联网 发布:高压清洗机品牌 知乎 编辑:程序博客网 时间:2024/06/04 17:57

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.

改变矩阵的形状

方法:一个一个复制,时间复杂度O(nm),额外空间复杂度O(1)

class Solution {public:    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {        int ro=nums.size();        if(ro==0) return nums;        int co=nums[0].size();        if(r*c!=ro*co) return nums;        vector<vector<int>> res(r,vector<int>(c,0));        int io=0,jo=0;//原数组的行和列标号        for(int i=0;i<r;i++)        {                       for(int j=0;j<c;j++)            {                 if(jo==co)//当一行复制完,移动到下一行            {                jo=0;                io++;            }                res[i][j]=nums[io][jo++];            }        }        return res;    }};


0 0
原创粉丝点击