Implement the class SubrectangleQueries which receives a rows x cols rectangle as a matrix of integers in the constructor and supports two methods:
1.updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)
Updates all values with newValue in the subrectangle whose upper left coordinate is (row1,col1) and bottom right coordinate is (row2,col2).
2.getValue(int row, int col)
Returns the current value of the coordinate (row,col) from the rectangle.
题目大意:实现类SubrectangleQueries, 接收整数矩阵在构造函数中且支持两种方法
- updateSubrectangle(int row1, int row2, int col1, int col2, int newVaule)更新左上角坐标为(row1, col1),右下角坐标为(row2, col2)的子矩阵,值为newValue
- getValue(int row, int col) 返回坐标为(row, col)的当前值
题目本身挺简单的
思路1:时间换空间,在方法updateSubrectangle中更新矩阵的值。
class SubrectangleQueries:
def __init__(self, rectangle: List[List[int]]):
self.data = rectangle
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
for i in range(row1, row2 + 1):
for j in range(col1, col2 + 1):
self.data[i][j] = newValue
def getValue(self, row: int, col: int) -> int:
return self.data[row][col]
思路2:空间换时间,在方法updateSubrectangle中不对矩阵进行更新,将更新信息存储起来,调用方法getValue中返回值
时先查看返回值是否在该子矩阵内。
class SubrectangleQueries:
def __init__(self, rectangle:List[List[int]]):
self.data = rectangle
self.updata = []
def updateSubrectangle(self, row1: int, col1: int, row2: int, col2: int, newValue: int) -> None:
self.update.append((row1, col1, row2, col2, newValue))
def getValue(self, row: int, col: int) -> int:
res = None
#注意这里range函数的用法
for i in range(len(self.update)-1, -1, -1):
row1, col1, row2, col2, val = self.update[i]
if row1 <= row <= row2 and col1 <= col <= col2:
res = val
break
return res if res else self.data[row][col]