leetcode:数组:1467自矩形查询

题目描述

请你实现一个类 SubrectangleQueries ,它的构造函数的参数是一个 rows x cols 的矩形(这里用整数矩阵表示),并支持以下两种操作:1. updateSubrectangle(int row1, int col1, int row2, int col2, int newValue)
用 newValue 更新以 (row1,col1) 为左上角且以 (row2,col2) 为右下角的子矩形。
2. getValue(int row, int col)
返回矩形中坐标 (row,col) 的当前值。

实例:

输入:
[“SubrectangleQueries”,“getValue”,“updateSubrectangle”,“getValue”,“getValue”,“updateSubrectangle”,“getValue”,“getValue”]
[[[[1,2,1],[4,3,4],[3,2,1],[1,1,1]]],[0,2],[0,0,3,2,5],[0,2],[3,1],[3,0,3,2,10],[3,1],[0,2]]
输出:
[null,1,null,5,5,null,10,5]
解释:
SubrectangleQueries subrectangleQueries = new SubrectangleQueries([[1,2,1],[4,3,4],[3,2,1],[1,1,1]]);
// 初始的 (4x3) 矩形如下:
// 1 2 1
// 4 3 4
// 3 2 1
// 1 1 1
subrectangleQueries.getValue(0, 2); // 返回 1
subrectangleQueries.updateSubrectangle(0, 0, 3, 2, 5);
// 此次更新后矩形变为:
// 5 5 5
// 5 5 5
// 5 5 5
// 5 5 5
subrectangleQueries.getValue(0, 2); // 返回 5
subrectangleQueries.getValue(3, 1); // 返回 5
subrectangleQueries.updateSubrectangle(3, 0, 3, 2, 10);
// 此次更新后矩形变为:
// 5 5 5
// 5 5 5
// 5 5 5
// 10 10 10
subrectangleQueries.getValue(3, 1); // 返回 10
subrectangleQueries.getValue(0, 2); // 返回 5

题目比较简单,list是不能跟numpy数组一样 list[a:b][c:d],有没有比较好的赋值方法我目前也没有探索出来。
这道题主要就是在子矩阵的构造。简单做法是通过两个for循环,一个for循环里面嵌套另一个for循环,时间复杂度是 O ( n 2 ) O(n^2) O(n2),可以改成是 O ( m + n ) O(m+n) O(m+n)。先构造出每一行要替代的list,在逐行替代。
如果我们要对list某一行一部分元素赋值,比如下面,是会can only assign an iterable错误的。因为20不能迭代,这个时候可以写成(20,),但是这个时候这一部分只会给1个20替代。

a = [[1,2,3],[4,5,6],[7,8,9]]
a[0][0:1] = 20
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
>>> a[0][0:2] = (20,)
>>> a
[[20, 3], [4, 5, 6], [7, 8, 9]]

class SubrectangleQueries(object):

    def __init__(self, rectangle):
        """
        :type rectangle: List[List[int]]
        """
        # print(rectangle)
        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
        """
        replace = []
        for i in range(col1, col2 + 1):
            replace.append(newValue)
        for j in range(row1, row2 + 1):
            self.rectangle[j][col1:col2 + 1] = replace
        # print(self.rectangle)
     

    def getValue(self, row, col):
        """
        :type row: int
        :type col: int
        :rtype: int
        """
        
        return self.rectangle[row][col]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值