LeetCode 1253: Reconstruct a 2-Row Binary Matrix

ArrayGreedyMatrix

Problem Description

Explanation

To reconstruct the 2-row binary matrix, we can iterate through the colsum array and fill in the matrix row by row. We will start by initializing an empty matrix and then iterate through each column. At each column, we will consider the sum needed for the upper row and lower row separately. If the current column has a value of 2, we can easily assign 1 to both rows. If the current column has a value of 1, we need to be careful to ensure that the upper and lower row sums are maintained correctly. If the current column has a value of 0, we can assign 0 to both rows. Finally, if after processing all columns, the upper and lower row sums match the given values, we return the reconstructed matrix; otherwise, we return an empty matrix.

Solutions

class Solution {
    public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) {
        int n = colsum.length;
        List<List<Integer>> matrix = new ArrayList<>();
        List<Integer> upperRow = new ArrayList<>();
        List<Integer> lowerRow = new ArrayList<>();
        
        for (int i = 0; i < n; i++) {
            if (colsum[i] == 2) {
                upperRow.add(1);
                lowerRow.add(1);
                upper--;
                lower--;
            } else if (colsum[i] == 1) {
                if (upper > lower) {
                    upperRow.add(1);
                    lowerRow.add(0);
                    upper--;
                } else {
                    upperRow.add(0);
                    lowerRow.add(1);
                    lower--;
                }
            } else {
                upperRow.add(0);
                lowerRow.add(0);
            }
        }
        
        if (upper == 0 && lower == 0) {
            matrix.add(upperRow);
            matrix.add(lowerRow);
            return matrix;
        } else {
            return new ArrayList<>();
        }
    }
}

Loading editor...