Submatrix Sum
Given an integer matrix, find a submatrix where the sum of numbers is zero. Your code should return the coordinate of the left-up and right-down number.
Subarray Sum的follow up。求二维矩阵上和为0的submatrix.
这题暴力解法枚举左上两坐标,右下两坐标,求中间和。复杂度为O(n^6)。太高。
比较好的办法是枚举子矩阵的开始行和结束行,之后以subarray sum的思路,用hashmap发现左边界和右边界。
为了高效求的开始行和结束行之间每一列的sum,可以先求得以(0,0)开始,右下坐标结束的submatrix sum。复杂度为O(m,n)。这一点比较神奇。
总体复杂度为O(n^2*m).代码如下:
class Solution: # @param {int[][]} matrix an integer matrix # @return {int[][]} the coordinate of the left-up and right-down number def submatrixSum(self, matrix): """ 1.enumerate the down-right corner, compute the sum firstly 2.enumerate the begin line and end line, find the submatrix just like the subarry(traverse the right line) """ res = [[0,0],[0,0]] if not matrix or not matrix[0]: return res m = len(matrix) n = len(matrix[0]) presum = [[0] * (n+1) for i in xrange(m+1)] for i in xrange(m): #求以(0,0)开始,右下坐标结束的子矩阵的复杂度。 for j in xrange(n): presum[i+1][j+1] = presum[i][j+1] + presum[i+1][j] - presum[i][j] + matrix[i][j] for l in xrange(m): for h in xrange(l+1,m+1): hash = {} for r in xrange(0, n+1): diff = presum[h][r] - presum[l][r] if diff not in hash: hash[diff] = r else: res[0][0] = l res[0][1] = hash[diff] res[1][0] = h - 1 res[1][1] = r-1 return res
posted on 2016-07-22 22:56 Sheryl Wang 阅读(376) 评论(0) 编辑 收藏 举报