2022. Convert 1D Array Into 2D Array | Leetcode POTD Explained

แชร์
ฝัง
  • เผยแพร่เมื่อ 5 พ.ย. 2024

ความคิดเห็น • 1

  • @codeby_naruto
    @codeby_naruto  2 หลายเดือนก่อน +2

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