forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
subrectangle-queries.py
71 lines (60 loc) · 1.72 KB
/
subrectangle-queries.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# Time: ctor: O(1)
# update: O(1)
# get: O(u), u is the number of updates
# Space: O(u)
class SubrectangleQueries(object):
def __init__(self, rectangle):
"""
:type rectangle: List[List[int]]
"""
self.__rectangle = rectangle
self.__updates = []
def updateSubrectangle(self, row1, col1, row2, col2, newValue):
"""
:type row1: int
:type col1: int
:type row2: int
:type col2: int
:type newValue: int
:rtype: None
"""
self.__updates.append((row1, col1, row2, col2, newValue))
def getValue(self, row, col):
"""
:type row: int
:type col: int
:rtype: int
"""
for (row1, col1, row2, col2, newValue) in reversed(self.__updates):
if row1 <= row <= row2 and col1 <= col <= col2:
return newValue
return self.__rectangle[row][col]
# Time: ctor: O(1)
# update: O(m * n)
# get: O(1)
# Space: O(1)
class SubrectangleQueries2(object):
def __init__(self, rectangle):
"""
:type rectangle: List[List[int]]
"""
self.__rectangle = rectangle
def updateSubrectangle(self, row1, col1, row2, col2, newValue):
"""
:type row1: int
:type col1: int
:type row2: int
:type col2: int
:type newValue: int
:rtype: None
"""
for r in xrange(row1, row2+1):
for c in xrange(col1, col2+1):
self.__rectangle[r][c] = newValue
def getValue(self, row, col):
"""
:type row: int
:type col: int
:rtype: int
"""
return self.__rectangle[row][col]