3.3 KiB
Leetcode Reshape-The-Matrix
2022-06-12
Data structures:
#DS #array #vector
Difficulty:
#leetcode #coding_problem #difficulty-easy
Related topics:
(tag:#array OR tag:#vector) -tag:#Kadane_s_algorithm
- Binary Search Algorithm
- cpp_Range_based_for_loop
- Leetcode Binary-Search
- Leetcode First-Bad-Version
- Leetcode First-Unique-Character-In-a-String
- Leetcode Merge-Sorted-Array
- Leetcode Pascal's-Triangle
- Leetcode Ransom-Note
- Leetcode Search-a-2D-Matrix
- Leetcode Search-Insert-Position
- Leetcode Two-Sum
- Leetcode Valid-Anagram
- Leetcode Valid-Sudoku
- Two pointers approach
Links:
Problem
In MATLAB, there is a handy function called reshape
which can reshape an m x n
matrix into a new one with a different size r x c
keeping its original data.
You are given an m x n
matrix mat
and two integers r
and c
representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped matrix should 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.
Examples
**Input:** mat = [[1,2],[3,4]], r = 1, c = 4
**Output:** [[1,2,3,4]]
Constraints
- m == mat.length
- n == mat[i].length
- 1 <= m, n <= 100
- -1000 <= mat[i][j] <= 1000
- 1 <= r, c <= 300
Thoughts
First is the O(mn) solution, I use nested for loop with two additional vars
Then, from the hint, I know we can transform any array to 1-D, then transform 1-D to any array, that is to said:
[!summary] For arr[m][n] and ans[r][c] and iterator i, with temp 1-D array temp[i]: temp[i] = arr[i / n][i % n] = ans[i / c][i % c]
Solution
O(nm) solution using two loops
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>> &mat, int r, int c) {
// Initialize the answer vector
vector<vector<int>> ans(r);
for (int i = 0; i < ans.size(); i++) {
ans[i] = vector<int>(c);
}
// if the vector is not possible, return original.
if (mat[0].size() * mat.size() != r * c) {
return mat;
}
int rCounter = 0;
int cCounter = 0;
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[i].size(); j++) {
if (cCounter >= c) {
rCounter++;
cCounter = cCounter % c;
}
ans[rCounter][cCounter++] = mat[i][j];
}
}
return ans;
}
};
O(mn) Solution using one loop
Tip
use
vector<vector<int>> ans(r, vector<int>(c));
to initialize a 2-d vector
class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>> &mat, int r, int c) {
// Initialize the answer vector
vector<vector<int>> ans(r, vector<int>(c));
int m = mat.size();
int n = mat[0].size();
int total = m * n;
// if the vector is not possible, return original.
if (total != r * c) {
return mat;
}
for (int i = 0; i < total; i++) {
ans[i / c][i % c] = mat[i / n][i % n];
}
return ans;
}
};