Code :- class Solution { public: vector construct2DArray(vector& original, int m, int n) { int totalElements = original.size(); // Total number of elements in the original array // If the total number of elements doesn't match the expected size of the 2D array, return an empty array if (totalElements != m * n) return vector(); vector result(m); // Initialize a 2D vector with 'm' rows int currentColumnCount = 0; // Counter for the number of elements in the current row int currentRow = 0; // Index for the current row for (int i = 0; i < totalElements; i++) { result[currentRow].push_back(original[i]); // Add the current element to the current row currentColumnCount++; // Increment the column counter // If the current row is filled, move to the next row if (currentColumnCount == n) { currentRow++; currentColumnCount = 0; // Reset the column counter for the new row } } return result; // Return the constructed 2D array } };
Code :-
class Solution {
public:
vector construct2DArray(vector& original, int m, int n) {
int totalElements = original.size(); // Total number of elements in the original array
// If the total number of elements doesn't match the expected size of the 2D array, return an empty array
if (totalElements != m * n) return vector();
vector result(m); // Initialize a 2D vector with 'm' rows
int currentColumnCount = 0; // Counter for the number of elements in the current row
int currentRow = 0; // Index for the current row
for (int i = 0; i < totalElements; i++) {
result[currentRow].push_back(original[i]); // Add the current element to the current row
currentColumnCount++; // Increment the column counter
// If the current row is filled, move to the next row
if (currentColumnCount == n) {
currentRow++;
currentColumnCount = 0; // Reset the column counter for the new row
}
}
return result; // Return the constructed 2D array
}
};