Leetcode 566. 重塑矩阵 (简单的实现Matlabreshape)

这道题目比较简单,先将二维数组转化为一维表示,在转化为另一个二维表示,实际上,中间转化为一维表示的过程可以省去。

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>> ans(r, vector<int>(c));
        for (int x = 0; x < m * n; ++x) {
            ans[x / c][x % c] = nums[x / n][x % n];
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/wwxy1995/article/details/113830070