您的位置:首页 > 产品设计 > UI/UE

Leetcode: Range Sum Query 2D - Immutable

2015-12-30 10:39 411 查看

Question

Range Sum Query 2D - Immutable My Submissions Question

Total Accepted: 5239 Total Submissions: 25173 Difficulty: Medium

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Range Sum Query 2D

The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.

Example:

Given matrix = [

[3, 0, 1, 4, 2],

[5, 6, 3, 2, 1],

[1, 2, 0, 1, 5],

[4, 1, 0, 1, 7],

[1, 0, 3, 0, 5]

]

sumRegion(2, 1, 4, 3) -> 8

sumRegion(1, 1, 2, 2) -> 11

sumRegion(1, 2, 2, 4) -> 12

Note:

You may assume that the matrix does not change.

There are many calls to sumRegion function.

You may assume that row1 ≤ row2 and col1 ≤ col2.

Hide Tags Dynamic Programming

Hide Similar Problems (E) Range Sum Query - Immutable (H) Range Sum Query 2D - Mutable

Have you met this question in a real interview? Yes No

Discuss

Solution

[code]class NumMatrix(object):
    def __init__(self, matrix):
        """
        initialize your data structure here.
        :type matrix: List[List[int]]
        """

        if len(matrix)!=0 and len(matrix[0])!=0:   
            m, n = len(matrix), len(matrix[0])
            self.sum = [ [0]*n for dummy in range(m) ] 

            self.sum[0][0] = matrix[0][0]
            for ind in range(1,m):
                self.sum[ind][0] = self.sum[ind-1][0] +  matrix[ind][0]

            for ind in range(1,n):
                self.sum[0][ind] = self.sum[0][ind-1] +  matrix[0][ind]

            for i in range(1,m):
                for j in range(1,n):
                    self.sum[i][j] = matrix[i][j] + self.sum[i-1][j] + self.sum[i][j-1] - self.sum[i-1][j-1]
        else:
            self.sum = -1

    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
        """

        #print self.sum
        if self.sum==-1:
            return 0

        if row1==0 and col1==0:
            return self.sum[row2][col2]

        if row1==0:
            return self.sum[row2][col2] - self.sum[row2][col1-1]

        if col1==0:
            return self.sum[row2][col2] - self.sum[row1-1][col2]

        return self.sum[row2][col2] + self.sum[row1-1][col1-1] - self.sum[row2][col1-1] - self.sum[row1-1][col2]

# Your NumMatrix object will be instantiated and called as such:
# numMatrix = NumMatrix(matrix)
# numMatrix.sumRegion(0, 1, 2, 3)
# numMatrix.sumRegion(1, 2, 3, 4)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: