forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathfind-valid-matrix-given-row-and-column-sums.py
40 lines (37 loc) · 1.32 KB
/
find-valid-matrix-given-row-and-column-sums.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# Time: O(m + n), excluding ctor of result
# Space: O(1)
# optimized from Solution2 since we can find next i, j pair without nested loops
class Solution(object):
def restoreMatrix(self, rowSum, colSum):
"""
:type rowSum: List[int]
:type colSum: List[int]
:rtype: List[List[int]]
"""
matrix = [[0]*len(colSum) for _ in xrange(len(rowSum))]
i = j = 0
while i < len(matrix) and j < len(matrix[0]):
matrix[i][j] = min(rowSum[i], colSum[j]) # greedily used
rowSum[i] -= matrix[i][j]
colSum[j] -= matrix[i][j]
if not rowSum[i]: # won't be used in row i, ++i
i += 1
if not colSum[j]: # won't be used in col j, ++j
j += 1
return matrix
# Time: O(m * n)
# Space: O(1)
class Solution2(object):
def restoreMatrix(self, rowSum, colSum):
"""
:type rowSum: List[int]
:type colSum: List[int]
:rtype: List[List[int]]
"""
matrix = [[0]*len(colSum) for _ in xrange(len(rowSum))]
for i in xrange(len(matrix)):
for j in xrange(len(matrix[i])):
matrix[i][j] = min(rowSum[i], colSum[j]) # greedily used
rowSum[i] -= matrix[i][j]
colSum[j] -= matrix[i][j]
return matrix