Sponsored
Sponsored
The greedy approach involves iterating over the matrix and at each cell (i, j), filling it with the minimum of the current rowSum[i] and colSum[j]. This method works because as we fill the matrix, we can always satisfy both the row and column conditions by subtracting the filled value from each.
Move through the matrix, adjusting row and column sums at each step. This continues until we've filled the entire matrix, ensuring the integrity of both row and column sum conditions.
Time Complexity: O(m + n), where m and n are the lengths of rowSum and colSum respectively, as we're adjusting values once per index.
Space Complexity: O(m * n) for storing the matrix.
1import java.util.List;
2import java.util.ArrayList;
3
4public class Solution {
5 public int[][] restoreMatrix(int[] rowSum, int[] colSum) {
6 int m = rowSum.length;
7 int n = colSum.length;
8 int[][] matrix = new int[m][n];
9 int i = 0, j = 0;
10 while (i < m && j < n) {
11 int fill = Math.min(rowSum[i], colSum[j]);
12 matrix[i][j] = fill;
13 rowSum[i] -= fill;
14 colSum[j] -= fill;
15 if (rowSum[i] == 0) i++;
16 if (colSum[j] == 0) j++;
17 }
18 return matrix;
19 }
20}
This Java solution sets up a similar procedure to the previously outlined logic, appropriately filling each cell based on the minimum of the current row sum and column sum. Row and column pointers are also incrementally updated to ensure all cells are processed.