leetcode1476

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, 接收整数矩阵在构造函数中且支持两种方法

  1. updateSubrectangle(int row1, int row2, int col1, int col2, int newVaule)更新左上角坐标为(row1, col1),右下角坐标为(row2, col2)的子矩阵,值为newValue
  2. 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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值