2023-06-29 LeetCode daily question (reconstruct 2 rows of binary matrix)

2023-06-29 One question per day

1. Topic number

1253. 重构 2 行二进制矩阵

2. Topic link

Click to jump to the topic location

3. Topic description

Given a binary array with 2 rows and n columns:

  • The matrix is ​​a binary matrix, which means that each element in the matrix is ​​either 0 or 1.
  • The sum of the elements in row 0 is upper.
  • The sum of the elements in row 1 is lower.
  • The sum of elements in column i (numbered from 0) is colsum[i], where colsum is an integer array of length n.

You need to use upper, lower and colsum to reconstruct this matrix and return it as a two-dimensional array of integers.

If there are multiple different answers, any one can pass the question.

If there is no answer that meets the requirements, please return an empty two-dimensional array.

hint:

  • 1 <= colsum.length <= 105
  • 0 <= upper, lower <= colsum.length
  • 0 <= colsum[i] <= 2

4. Problem solving code

class Solution {
    
    
public:
    vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {
    
    
        int n = colsum.size();
        int sum = 0, two = 0;
        for (int i = 0; i < n; ++i) {
    
    
            if (colsum[i] == 2) {
    
    
                ++two;
            }
            sum += colsum[i];
        }
        if (sum != upper + lower || min(upper, lower) < two) {
    
    
            return {
    
    };
        }
        upper -= two;
        lower -= two;
        vector<vector<int>> res(2, vector<int>(n, 0));
        for (int i = 0; i < n; ++i) {
    
    
            if (colsum[i] == 2) {
    
    
                res[0][i] = res[1][i] = 1;
            } else if (colsum[i] == 1) {
    
    
                if (upper > 0) {
    
    
                    res[0][i] = 1;
                    --upper;
                } else {
    
    
                    res[1][i] = 1;
                }
            }
        }
        return res;
    }
};

Five, problem-solving ideas

(1) Use greedy thinking to solve this problem.

Guess you like

Origin blog.csdn.net/qq_56086076/article/details/131448620