Problem Description
Explanation:
To solve this problem, we can construct the matrix iteratively by assigning values to each cell. We start by initializing an empty matrix of size rowSum.length x colSum.length
. Then, we iteratively fill in the matrix elements such that each row and column sum match the given rowSum
and colSum
arrays.
We can achieve this by iteratively assigning the minimum value between the remaining row sum and column sum in each cell, updating the corresponding row and column sums. This process continues until all row and column sums are satisfied.
The time complexity of this approach is O(n^2), where n is the maximum of rowSum.length and colSum.length. The space complexity is O(n^2) for the output matrix.
:
Solutions
class Solution {
public int[][] restoreMatrix(int[] rowSum, int[] colSum) {
int m = rowSum.length;
int n = colSum.length;
int[][] matrix = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = Math.min(rowSum[i], colSum[j]);
rowSum[i] -= matrix[i][j];
colSum[j] -= matrix[i][j];
}
}
return matrix;
}
}
Loading editor...