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.

解题思路:

这道题很简单,就是检查二维数组能否把两个维度大小改变一下仍能存下相同数量的元素。

代码如下:
//注意一下嵌套vector的初始化即可
class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        if (nums.size() * nums[0].size() == r * c) {
            vector<vector<int>> temp(r);
            for (int i = 0; i < r; ++i)
                temp[i].resize(c);
            for (int i = 0; i < r * c; ++i) {
                //通过求商和求余的方式来简化代码。
                temp[i / c][i % c] = nums[i / nums[0].size()][i % nums[0].size()];
            }
            return temp;
        }
        else {
            return nums;
        }
    }
};
//嵌套vector可以不初始化,但是应该不可以在用之前用下标给赋值了。
class Solution {
public:
    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
        if (nums.size() * nums[0].size() == r * c) {
            vector< vector <int> > temp;
            vector<int> temp2;
            for (int i = 0; i < nums.size(); ++i) {
                for (int j = 0; j < nums[0].size(); ++j) {
                    if (temp2.size() < c)
                        temp2.push_back(nums[i][j]);
                    else {
                        //push整个vector<int>
                        temp.push_back(temp2);
                        temp2.clear();
                        temp2.push_back(nums[i][j]);
                    }
                }
            }
            //push整个vector<int>
            temp.push_back(temp2);
            return temp;
        }
        else {
            return nums;
        }
    }
};
//注意一下二维数组动态申请内存的方法
public int[][] matrixReshape(int[][] nums, int r, int c) {
    int m = nums.length, n = nums[0].length;
    if (r * c != m * n)
        return nums;
    //动态分配,r和c都是变量
    int[][] reshaped = new int[r][c];
    for (int i = 0; i < r * c; i++)
        reshaped[i/c][i%c] = nums[i/n][i%n];
    return reshaped;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值