Skip to content

Commit 9b16daa

Browse files
authored
Create increment-submatrices-by-one.py
1 parent 4cb6370 commit 9b16daa

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Time: O(q + n^2)
2+
# Space: O(1)
3+
4+
# line sweep, difference matrix (2d difference array)
5+
class Solution(object):
6+
def rangeAddQueries(self, n, queries):
7+
"""
8+
:type n: int
9+
:type queries: List[List[int]]
10+
:rtype: List[List[int]]
11+
"""
12+
result = [[0]*n for _ in xrange(n)]
13+
for r1, c1, r2, c2 in queries:
14+
result[r1][c1] += 1
15+
if c2+1 < len(result[0]):
16+
result[r1][c2+1] -= 1
17+
if r2+1 < len(result):
18+
result[r2+1][c1] -= 1
19+
if r2+1 < len(result) and c2+1 < len(result[0]):
20+
result[r2+1][c2+1] += 1
21+
for r in xrange(len(result)):
22+
for c in xrange(len(result[0])-1):
23+
result[r][c+1] += result[r][c]
24+
for r in xrange(len(result)-1):
25+
for c in xrange(len(result[0])):
26+
result[r+1][c] += result[r][c]
27+
return result

0 commit comments

Comments
 (0)