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.
Example 1:
Input: rowSum = [3,8], colSum = [4,7] Output: [[3,0], [1,7]] Explanation: 0th row: 3 + 0 = 0 == rowSum[0] 1st row: 1 + 7 = 8 == rowSum[1] 0th column: 3 + 1 = 4 == colSum[0] 1st column: 0 + 7 = 7 == colSum[1] The row and column sums match, and all matrix elements are non-negative. Another possible matrix is: [[1,2], [3,5]]
Example 2:
Input: rowSum = [5,7,10], colSum = [8,6,8] Output: [[0,5,0], [6,1,0], [2,0,8]]
Example 3:
Input: rowSum = [14,9], colSum = [6,9,8] Output: [[0,9,5], [6,0,3]]
Example 4:
Input: rowSum = [1,0], colSum = [1] Output: [[1], [0]]
Example 5:
Input: rowSum = [0], colSum = [0] Output: [[0]]
Constraints:
1 <= rowSum.length, colSum.length <= 500
0 <= rowSum[i], colSum[i] <= 108
sum(rows) == sum(columns)
给定行和列的和求可行矩阵。
给你两个非负整数数组 rowSum 和 colSum ,其中 rowSum[i] 是二维矩阵中第 i 行元素的和, colSum[j] 是第 j 列元素的和。换言之你不知道矩阵里的每个元素,但是你知道每一行和每一列的和。
请找到大小为 rowSum.length x colSum.length 的任意 非负整数 矩阵,且该矩阵满足 rowSum 和 colSum 的要求。
请你返回任意一个满足题目要求的二维矩阵,题目保证存在 至少一个 可行矩阵。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-valid-matrix-given-row-and-column-sums
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是贪心。这道题跟1253题差不多但是个人感觉稍微难一点,尤其是证明贪心的正确性会是个难点。
我们首先创建一个二维数组 int[][] res 记录最后的结果,res的尺寸是 [rowSum.length][colSum.length]。接着我们遍历这个二维数组,对于每一个位置上的元素,我们写入 rowSum[i] 和 colSum[j] 的较小值,同时需要在 rowSum[i] 和 colSum[j]里面减去这个较小值。
证明:对于每一个位置 res[i][j],我们一开始写入 Math.min(rowSum[i], colSum[j]) 应该没有什么疑问,这样操作之后,会使得 rowSum[i], colSum[j] 之中有一个变成0。如此操作直到最后一个位置上的时候,理应让 sum(rows) 和 sum(columns) 都变成0。
时间O(m + n)
空间O(mn)
Java实现
1 class Solution { 2 public int[][] restoreMatrix(int[] rowSum, int[] colSum) { 3 int m = rowSum.length; 4 int n = colSum.length; 5 int[][] res = new int[m][n]; 6 for (int i = 0; i < m; i++) { 7 for (int j = 0; j < n; j++) { 8 res[i][j] = Math.min(rowSum[i], colSum[j]); 9 rowSum[i] -= res[i][j]; 10 colSum[j] -= res[i][j]; 11 } 12 } 13 return res; 14 } 15 }
相关题目
1253. Reconstruct a 2-Row Binary Matrix