566. Reshape the Matrix

Description:

https://leetcode.com/problems/reshape-the-matrix/#/description

Boundary:

r * c == r’ * c’?

Algorithm:

Store the data in one dim vector and evaluate the new r*c matrix

Code:

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 (r * c != m * n)
return nums;

vector<int> nums_all;
vector<vector<int>> nums_new = vector<vector<int>>(r, vector<int>(c, -1));
for (int k = 0; k < m; k++)
nums_all.insert(nums_all.end(), nums[k].begin(), nums[k].end());
int count = 0;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
nums_new[i][j] = nums_all[count++];
return nums_new;
}
};

Time:

 

Leave a Reply

Your email address will not be published. Required fields are marked *