[LeetCode]1605. Find a feasible matrix given the sum of rows and columns

Give you two non-negative integer arrays rowSum and colSum , where rowSum[i] is the in the two-dimensional matrix. /span>  column elements. In other words, you don’t know every element in the matrix, but you know the sum of each row and column.  is the sum of the i The sum of the row elements, colSum[j]j

Please find any non-negative integer matrix of size rowSum.length x colSum.length , and the matrix satisfies  requirements.  and rowSumcolSum

Please return any two-dimensional matrix that meets the requirements of the question. The question is guaranteed to exist at least one feasible matrix.

Example 1:

Input:rowSum = [3,8], colSum = [4,7]
Output: [[3,0],
      [1,7]]Explanation:
Row 0: 3 + 0 = 3 == rowSum[0]
Row 1: 1 + 7 = 8 == rowSum[1]
Column 0: 3 + 1 = 4 == colSum[0]
Column 1: 0 + 7 = 7 == colSum[1]
The sums of rows and columns meet the question requirements, and all matrix elements are non-negative. 
Another feasible matrix is: [[1,2],
                  [3,5]]

Example 2:

Import:rowSum = [5,7,10], colSum = [8,6,8]
Output:[[0,5,0],
      [6,1,0],
      [2,0,8]]

Example 3:

Import:rowSum = [14,9], colSum = [6,9,8]
Output:[[0,9,5],
      [6,0,3]]

Example 4:

Import:rowSum = [1,0], colSum = [1]
Output:[[1],
      [0]]

Example 5:

Import:rowSum = [0], colSum = [0]
Output:[[0]]

hint:

  • 1 <= rowSum.length, colSum.length <= 500
  • 0 <= rowSum[i], colSum[i] <= 108
  • sum(rowSum) == sum(colSum)

思路:Starting from the upper left corner, remove either a row or a column at a time. Every time min is found, just subtract it according to the conditions to determine whether to wrap the line or the column.

class Solution {
public:
    vector<vector<int>> restoreMatrix(vector<int>& rowSum, vector<int>& colSum) {//贪心
        int row = rowSum.size();
        int col = colSum.size();
        vector<vector<int>> ans(row,vector<int>(col));//初始化二维数组
        for(int i=0,j=0;i<row&&j<col;){
            if(rowSum[i]>colSum[j]){//换列
                rowSum[i]-=colSum[j];
                ans[i][j++] = colSum[j];
            }
            else {//换行
                colSum[j]-=rowSum[i];
                ans[i++][j] = rowSum[i];
            }
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/bigBbug/article/details/129524394