Submatrix Sum
[ [1 ,5 ,7], [3 ,7 ,-8], [4 ,-8 ,9], ]
def submatrixSum(self, matrix):
# 没做做数组为空的检查,认为test case 给有效的matrix
m, n = len(matrix), len(matrix[0])
accu = [ [0] * (n + 1) for _ in xrange(m + 1)]
for i in xrange(1, m + 1):
for j in xrange(1, n + 1):
accu[i][j] = accu[i - 1][j] + accu[i][j - 1] \
+ matrix[i - 1][j - 1] - accu[i - 1][j - 1]
for lo in xrange(m + 1):
for hi in xrange(lo + 1, m + 1):
hashmap = dict()
for j in xrange(n + 1):
target = accu[hi][j] - accu[lo][j] # 就如一维数组的情况下,希望找到前面有相同的 prefix sum
if target in hashmap: # 那么两个坐标之间的 sub array sum = 0
k = hashmap[target] # 这里是类似的思想,在lo和hi确定的情况下,把lo和hi夹着的长条
return [(lo, k), (hi - 1, j - 1)] # 当作1维来处理
else:
hashmap[target] = j
return []Last updated
