LeetCode | 566. Reshape the Matrix

来源:互联网 发布:士兵伙食知乎 编辑:程序博客网 时间:2024/05/29 13:59


题目:

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.


例子:

Input: nums = [[1,2], [3,4]]r = 1, c = 4Output: [[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.


题意:大意就是要求将输入的矩阵变换为指定尺寸的形式,要求初始矩阵的长宽乘row * col == r * c;若不满足以上要求则返回原数组。


思路分析:

因为难度是Easy,所以思路比较简单,数据范围的提示也很小,所以直接做即可。首先对输入矩阵尺寸进行判断,如果符合要求则变换坐标。一次AC,^___________________^*


代码:运行时间39ms

vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {        vector<vector<int>> res;        int row = nums.size();        if(row < 1)            return res;        int col = nums[0].size();        if(col < 1)            return res;        if(row * col != r * c){            res = nums;            return res;        }res = vector<vector<int>>(r, vector<int>(c));for(int i = 0; i<r*c; i++){int idx1 = i/col, idy1 = i%col;int idx2 = i/c, idy2 = i%c;res[idx2][idy2] = nums[idx1][idy1];}return res;    }


最近Leet上面出了很多新题,哈哈哈加油AC~


题外话:Ode to Joy 2启程啦!哈哈哈哈忍不住偷看了两眼!加油!






1 0
原创粉丝点击