8.16 - hard - 60

308. Range Sum Query 2D - Mutable

这题所谓的标准解法是用segment tree或者indexed tree(indexed tree我没用过,都不知道是什么)。其实只要用简单的前缀和数组就可以解决。

class NumMatrix(object):

    def __init__(self, matrix):
        """
        initialize your data structure here.
        :type matrix: List[List[int]]
        """
        for row in matrix:
            for col in xrange(1, len(row)):
                row[col] += row[col-1]
        self.matrix = matrix
        

    def update(self, row, col, val):
        """
        update the element at matrix[row,col] to val.
        :type row: int
        :type col: int
        :type val: int
        :rtype: void
        """
        original = self.matrix[row][col]
        if col != 0:
            original -= self.matrix[row][col-1]
            
        diff = original - val
        
        for y in xrange(col, len(self.matrix[0])):
            self.matrix[row][y] -= diff

    def sumRegion(self, row1, col1, row2, col2):
        """
        sum of elements matrix[(row1,col1)..(row2,col2)], inclusive.
        :type row1: int
        :type col1: int
        :type row2: int
        :type col2: int
        :rtype: int
        """
        sum = 0
        for x in xrange(row1, row2+1):
            sum += self.matrix[x][col2]
            if col1 != 0:
                sum -= self.matrix[x][col1-1]
        return sum
        


# Your NumMatrix object will be instantiated and called as such:
# obj = NumMatrix(matrix)
# obj.update(row,col,val)
# param_2 = obj.sumRegion(row1,col1,row2,col2)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,348评论 0 33
  • Onsite talk 1.了解自己的项目细节 Question: 1.思考BST level order tra...
    Uchiha朵朵阅读 2,622评论 0 0
  • 一晃神儿,才发现自己已经二十岁了,二十岁,我到底应该怎么做,到现在,我还是没有想明白。 年轻就是要使劲儿折腾。是,...
    温眸顾你阅读 1,820评论 0 1
  • 那时候,秋千架晃悠晃悠的。 我的怀里有着小宝宝,身边坐着大宝宝。 相对而坐,无需说话。 日子一点点过去,不留痕迹。...
    婉妹纸阅读 1,072评论 0 1
  • 么么么,宝贝今天的5分钟 好惊喜,好惊讶,好开心,199了,每天的每天,不一样的每一天,199个不一样的精彩日子,...
    握着荆条阅读 864评论 0 0