forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 6
/
range-sum-query-2d-mutable.py
82 lines (74 loc) · 2.32 KB
/
range-sum-query-2d-mutable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# Time: ctor: O(mlogm * nlogn)
# update: O(logm * logn)
# query: O(logm * logn)
# Space: O(m * n)
# Binary Indexed Tree (BIT) solution.
class NumMatrix(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
if not matrix:
return
self.__matrix = matrix
self.__bit = [[0] * (len(self.__matrix[0]) + 1) \
for _ in xrange(len(self.__matrix) + 1)]
for i in xrange(len(self.__matrix)):
for j in xrange(len(self.__matrix[0])):
self.__add(i, j, matrix[i][j])
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
"""
if val - self.__matrix[row][col]:
self.__add(row, col, val - self.__matrix[row][col])
self.__matrix[row][col] = val
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
"""
def sumRegion_bit(row, col):
row += 1
col += 1
ret = 0
i = row
while i > 0:
j = col
while j > 0:
ret += self.__bit[i][j]
j -= (j & -j)
i -= (i & -i)
return ret
ret = sumRegion_bit(row2, col2)
if row1 > 0 and col1 > 0:
ret += sumRegion_bit(row1 - 1, col1 - 1)
if col1 > 0:
ret -= sumRegion_bit(row2, col1 - 1)
if row1 > 0:
ret -= sumRegion_bit(row1 - 1, col2)
return ret
def __add(self, row, col, val):
row += 1
col += 1
i = row
while i <= len(self.__matrix):
j = col
while j <= len(self.__matrix[0]):
self.__bit[i][j] += val
j += (j & -j)
i += (i & -i)
# Your NumMatrix object will be instantiated and called as such:
# numMatrix = NumMatrix(matrix)
# numMatrix.sumRegion(0, 1, 2, 3)
# numMatrix.update(1, 1, 10)
# numMatrix.sumRegion(1, 2, 3, 4)