Leetcode:1605. Find Valid Matrix Given Row and Column Sums 给定行和列的和求可行矩阵

You are given two arrays rowSum and colSum of non-negative integers where rowSum[i] is the sum of the elements in the ith row and colSum[j] is the sum of the elements of the jth column of a 2D matrix. In other words, you do not know the elements of the matrix, but you do know the sums of each row and column.

Find any matrix of non-negative integers of size rowSum.length x colSum.length that satisfies the rowSum and colSum requirements.

Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists.

分析:

每个的值必须要小于 当前行的和and当前列的和 所以为  min(rs[i], cs[j])并且对每行的和 and 每列的和进行更新 (-val)

代码:

class Solution {
public:
    vector<vector<int>> restoreMatrix(vector<int>& rowSum, vector<int>& colSum) {
        int m = rowSum.size();
        int n = colSum.size();
        vector<vector<int>> res(m, vector<int>(n, 0));
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                int val = min(rowSum[i], colSum[j]);
                res[i][j] = val;
                rowSum[i] -= val;
                colSum[j] -= val;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44189622/article/details/129540416