---
# System prepended metadata

title: 1605. Find Valid Matrix Given Row and Column Sums
tags: [Leetcode, Medium, Greedy]

---

# 1605. Find Valid Matrix Given Row and Column Sums
###### tags: `Leetcode` `Medium` `Greedy`
Link: https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/
## 思路 $O(mn)$ $O(1)$
每次把rowsum和colsum里面比较小的那个拿出来当当前位置的值，然后再把rowsum，colsum减掉对应的值
## Code
```java=
class Solution {
    public int[][] restoreMatrix(int[] rowSum, int[] colSum) {
        int[][] res = new int[rowSum.length][colSum.length];
        for(int i = 0;i < rowSum.length;i++){
            for(int j = 0;j < colSum.length;j++){
                res[i][j] = Math.min(rowSum[i], colSum[j]);
                rowSum[i] -= res[i][j];
                colSum[j] -= res[i][j];
            }
        }
        return res;
    }
}
```