Leetcode 566. Reshape the matrix (simple realization of Matlab reshape)

 

This question is relatively simple, first convert a two-dimensional array into a one-dimensional representation, and then into another two-dimensional representation. In fact, the process of converting to a one-dimensional representation can be omitted.

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;
    }
};

 

Guess you like

Origin blog.csdn.net/wwxy1995/article/details/113830070