leecode:配列:1467自己長方形クエリ

タイトル説明

コンストラクターパラメーターが行x列の長方形(ここでは整数行列で表されます)であるクラスSubrectangleQueriesを実装し、次の2つの操作をサポートしてください。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を返します

トピックは比較的単純です。リストをnumpy配列リスト[a:b] [c:d]と同じにすることはできません。より良い割り当て方法があるかどうかについては調べていません。
この質問は、主にサブマトリックスの構築に関するものです。簡単な方法は、2つのforループを渡すことです。1つのforループは別のforループ内にネストされ、時間計算量はO(n 2)O(n ^ 2)です。O n2O(m + n)O(m + n)に変更できますO m+n まず、行ごとに置き換えるリストを作成し、行ごとに置き換えます。
次のように、リストの行の一部に値を割り当てたい場合は、反復可能なエラーしか割り当てることができません。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]

おすすめ

転載: blog.csdn.net/eight_Jessen/article/details/113531016