1605. Find Valid Matrix Given Row and Column Sums

• Time: $O(mn)$
• Space: $O(mn)$
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Solution { public: vector> restoreMatrix(vector& rowSum, vector& colSum) { const int m = rowSum.size(); const int n = colSum.size(); vector> ans(m, vector(n)); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { ans[i][j] = min(rowSum[i], colSum[j]); rowSum[i] -= ans[i][j]; colSum[j] -= ans[i][j]; } return ans; } }; 
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Solution { public int[][] restoreMatrix(int[] rowSum, int[] colSum) { final int m = rowSum.length; final int n = colSum.length; int[][] ans = new int[m][n]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { ans[i][j] = Math.min(rowSum[i], colSum[j]); rowSum[i] -= ans[i][j]; colSum[j] -= ans[i][j]; } return ans; } } 
  1 2 3 4 5 6 7 8 9 10 11 12 13 class Solution: def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: m = len(rowSum) n = len(colSum) ans = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): ans[i][j] = min(rowSum[i], colSum[j]) rowSum[i] -= ans[i][j] colSum[j] -= ans[i][j] return ans