LeetCode 566.Reshape the Matrix

来源:互联网 发布:xbox360 知乎 编辑:程序博客网 时间:2024/05/20 21:47

LeetCode 566.Reshape the Matrix

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.

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.

分析:

思路很简单,就是原二维数组的大小,也就是原矩阵的行和列的乘积,如果不等于reshape后的大小,即reshape不成功,返回原二维数组。

如果相等,则把原二维数组的每一个数放到新二维数组(起始行列均为0)中去,此时不断增加新二维数组的列,直到列大小等于reshape后的列的大小;然后就增大行大小,同时置列为0。

一个主要问题是需要初始化 vector<vector<int>>,否则会出现runtime error。

代码如下:

#include <iostream>#include <vector>using namespace std;class Solution {public:    vector<vector<int> > matrixReshape(vector<vector<int> >& nums, int r, int c) {        int r1 = nums.size();        int c1 = nums[0].size();        if (r1 * c1 != r * c) return nums;        vector<vector<int> > res(r, vector<int>(c, 0));// 这一步初始化二维非常重要        int rows = 0, cols = 0;        for (int i = 0; i < r1; i++) {            for (int j = 0; j < c1; j++) {                res[rows][cols] = nums[i][j];                cols++;                if (cols == c) {                    rows++;                    cols = 0;                }            }        }        return res;    }};int main() {    Solution s;    int r1, c1;    cin >> r1 >> c1;    vector<vector<int> > nums(r1, vector<int>(c1, 0));// 这一步初始化二维非常重要    int t;    for (int i = 0; i < r1; i++) {        for (int j = 0; j < c1; j++) {            //cin >> t;            cin >> nums[i][j];        }    }    int r, c;    cin >> r >> c;    vector<vector<int> > temp = s.matrixReshape(nums, r, c);    for (int i = 0; i < temp.size(); i++) {        for (int j = 0; j < temp[0].size(); j++) {            cout << temp[i][j] << " ";        }    }    return 0;}
原创粉丝点击