1.暴力法
class SubrectangleQueries(object):
def __init__(self, rectangle):
"""
:type rectangle: List[List[int]]
"""
self.data=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 i in range(row1,row2+1):
for j in range(col1,col2+1):
self.data[i][j]=newValue
def getValue(self, row, col):
"""
:type row: int
:type col: int
:rtype: int
"""
return self.data[row][col]
# Your SubrectangleQueries object will be instantiated and called as such:
# obj = SubrectangleQueries(rectangle)
# obj.updateSubrectangle(row1,col1,row2,col2,newValue)
# param_2 = obj.getValue(row,col)
2.数组变numpy形式的数组,利用numpy的切片赋值,一行语句完成赋值
3.保存更新值:不改变原数组中的数据,以空间换时间
class SubrectangleQueries:
def __init__(self, rectangle: List[List[int]]):
self.rectangle = rectangle
self.hash_map = {}
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
self.hash_map[(row1, col1, row2, col2)] = newValue
def getValue(self, row: int, col: int) -> int:
result = self.rectangle[row][col]
for row1, col1, row2, col2 in self.hash_map.keys():
if row1 <= row <= row2 and col1 <= col <= col2:
result = self.hash_map[(row1, col1, row2, col2)]
return result
# Your SubrectangleQueries object will be instantiated and called as such:
# obj = SubrectangleQueries(rectangle)
# obj.updateSubrectangle(row1,col1,row2,col2,newValue)
# param_2 = obj.getValue(row,col)
还可以用列表来代替哈希表,列表中可以是有序的,找到之后可以直接退出循环避免不必要的迭代